《Python编程快速上手—让繁琐工作自动化》第14章实践项目

14.8 Excel 到 CSV 的转换程序

from openpyxl import load_workbook
import csv,os

for excelFile in os.listdir('.'):
    if not excelFile.endswith('.xlsx'):
        continue
    wb = load_workbook(excelFile,data_only=True)
    for sheetName in wb.sheetnames:
        ws = wb[sheetName]

        File = open(excelFile.replace('.xlsx','')+'_'+sheetName + '.csv',
                        'w', newline='')
        rowData = []
        for row in range(1,ws.max_row+1):
           
            for col in range(1,ws.max_column+1):
                
                rowData.append(ws.cell(row=row,column=col).value)
            
            csvWriter = csv.writer(File)
            csvWriter.writerow(rowData)
            rowData = []
        File.close()

print('Done')

你可能感兴趣的:(《Python编程快速上手—让繁琐工作自动化》第14章实践项目)