SoFunction
Updated on 2024-11-12

python read excel table generate erlang data

In order to excel data automatically converted to the required erlang data, listening to colleagues say that the use of python will be very convenient and simple, on the self-taught two days python, wrote a relatively rough python script, but can be used, there are any optimization of the place please advise!

The code is as follows:

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
from  import load_workbook
import os
import 

def gen_data(filename):
 wb = load_workbook('dataxlsx/' + filename + '.xlsx') # Load all pages of the document

 sheetnames = wb.get_sheet_names() # Get a list of all paged names
 ws = wb.get_sheet_by_name(sheetnames[0]) # Fetch data from the first paging
# print 'ws:', ws

# print "Work Sheet Titile:", # paging name
# print "Work Sheet Rows:", ws.max_row # paginate rows
# print "Work Sheet Cols:", ws.max_column # paginate columns

 content = [] # Data content
 id_list = [] # ID List

# ========================start concat need data=================
 ('%% this file is auto maked!\n')
 ('-module(' + filename + ').\n')
 ('-compile(export_all).\n')

 for i in range(4, ws.max_row + 1):  # Read from the third line of the table, because the range function does not include the end of the file, so in order to read the last line need to +1
  for j in range(ws.max_column):
   if ws[i][j].value == None:
    (' ,""')
   elif j == 0:
    id_list.append(int(ws[i][j].value))
    ('get(' + str(ws[i][j].value).strip() + ') ->\n')
    (' {r_' + filename + ', ' + str(ws[i][j].value).strip())
   else:
    (' ,' + str(ws[i][j].value).strip())
  ('};\n')

 ('get(_) ->\n')
 (' not_match.\n')

 ('length() ->\n')
 (' ' + str(ws.max_row - 1) + '.\n')
 ('id_list() ->\n ' + str(id_list) + '.')
# ==============================end===========================
 # Write data
 f = file('./server/' + filename + '.erl','w+')
 (content)
 print 'create new file:', filename + '.erl'
 () # Close the channel
 return

def start_gen():
 # Delete old data
 delnames = ('./server')
 for delname in delnames:
  ('./server/' + delname)
  print 'delete old file:', delname

 for _, _, filenames in ('./dataxlsx'): # Traversing folders
  for filename in filenames: # Traversing the document
   find = ('.xlsx') # Returns the length of the file name
#   print "find is:", find
   if filename[0] == '~' or find == -1: # Files whose names start with '~' or whose names cannot be found, e.g., files starting with '. file starts with '.
    continue
   else:
    split_list = ('.') # Use '.' Split filename to get [filename,file format]
#    print split_list
    gen_data(split_list[0]) # Call gen_data with filename as argument

start_gen()

This is the whole content of this article.