Excel 到 CSV 的转换程序

xiaoxiao2021-03-01  107

Excel 可以将电子表格保存为 CSV 文件,只要点几下鼠标,但如果有几百个 Excel文件要转换为 CSV,就需要点击几小时。利用第 12 章的 openpyxl 模块, 编程读取当前工作目录中的所有 Excel 文件,并输出为 CSV 文件。一个 Excel 文件可能包含多个工作表,必须为每个表创建一个 CSV 文件。 CSV文件的文件名应该是<Excel 文件名>_<表标题>.csv,其中<Excel 文件名>是没有扩展名的 Excel 文件名(例如'spam_data',而不是'spam_data.xlsx'), <表标题>是Worksheet 对象的 title 变量中的字符串。该程序将包含许多嵌套的 for 循环。该程序的框架看起来像这样:

for excelFile in os.listdir('.'): # Skip non-xlsx files, load the workbook object. for sheetName in wb.get_sheet_names(): # Loop through every sheet in the workbook. sheet = wb.get_sheet_by_name(sheetName) # Create the CSV filename from the Excel filename and sheet title. # Create the csv.writer object for this CSV file. # Loop through every row in the sheet. for rowNum in range(1, sheet.get_highest_row() + 1): rowData = [] # append each cell to this list # Loop through each cell in the row. for colNum in range(1, sheet.get_highest_column() + 1): # Append each cell's data to rowData. # Write the rowData list to the CSV file. csvFile.close()

从 http://nostarch.com/automatestuff/下载 ZIP 文件 excelSpreadsheets.zip,将这些电子表格解压缩到程序所在的目录中。可以使用这些文件来测试程序。

代码

import csv, openpyxl, os os.makedirs('resultCSV', exist_ok=True) for excelFile in os.listdir('.\\excelSpreadsheets'): if not excelFile.endswith('.xlsx'): continue print('Converting file: ' + excelFile + '...') wb = openpyxl.load_workbook(os.path.join('.\\excelSpreadsheets' , excelFile)) for sheetName in wb.sheetnames: sheet = wb[sheetName] csvFile = excelFile[:-5] + '_' + sheet.title + '.csv' print('CSV FILE: ' + csvFile) csvFileObj = open(os.path.join('resultCSV', csvFile), 'w', newline='') csvWriter = csv.writer(csvFileObj) for rowNum in range(1, sheet.max_row + 1): rowData = [] for colNum in range(1, sheet.max_row + 1): rowData.append(sheet.cell(row=rowNum, column=colNum).value) csvWriter.writerow(rowData) csvFileObj.close()

 

转载请注明原文地址: https://www.6miu.com/read-4050155.html

最新回复(0)