Python Excel到CSV的转换 Python编程快速上手——Excel到CSV的转换程序案例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python Excel到CSV的转换 Python编程快速上手——Excel到CSV的转换程序案例分析

授我以驴   2021-04-21 我要评论

本文实例讲述了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()

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

思路如下:

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

代码如下:

#! 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()

运行结果:

希望本文所述对大家Python程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们