《Python编程快速上手》Excel到CSV的转换程序

题目如下:

  • 利用第十二章的openpyxl模块,编程读取当前工作目录中的所有Excel文件,并输出为csv文件。
  • 一个Excel文件可能包含多个工作表,必须为每个表创建一个CSV文件。CSV文件的文件名应该是<Excel 文件名>_<表标题>.csv,其中< Excel 文件名 >是没有拓展名的Excel文件名,<表标题>是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.max_row + 1):
                 rowData = [] #append each cell to this list
                 # loop through each cell in the row
                 for colNum in range (1, sheet.max_column + 1):
                       #Append each cell's data to rowData
                 # write the rowData list to CSV file
             csvFile.close()

思路如下:

  • 基本上按照题目给定的框架进行代码的编写
  • 对英文进行翻译,理解意思即可快速编写出程序

代码如下:

#! python3
import os, openpyxl, csv
for excelFile in os.listdir('.\\CSV'): #我将解压后的excel文件放入此文件夹
    # 筛选出excel文件,创建工作表对象
    if excelFile.endswith('.xlsx'):
        wb = openpyxl.load_workbook('.\\CSV\\'+ excelFile)
        for sheetName in wb.get_sheet_names():
            #依次遍历工作簿中的工作表
            sheet = wb.get_sheet_by_name(sheetName)
            #根据excel文件名和工作表名创建csv文件名
            #通过csv.writer创建csv file对象
            basename = excelFile[0:-5] #将excel文件名进行切割,去掉文件名后缀.xlsx
            File = open('{0}_{1}.csv'.format(basename,sheetName),'w') #新建csv file对象
            csvFile = csv.writer(File) #创建writer对象
            #csvFileWriter.writerow()
            #遍历表中每行
            for rowNum in range(1,sheet.max_row+1):
                rowData = [] #防止每个单元格内容的列表
                #遍历每行中的单元格
                for colNum in range(1,sheet.max_column + 1):
                    #将每个单元格数据添加到rowData
                    rowData.append(sheet.cell(row = rowNum,column = colNum).value)
                csvFile.writerow(rowData)
                #将rowData列表写入到csv file
            File.close()

运行结果:

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值