python编程快速上手之第14章实践项目参考答案(14.9)

本文介绍了一个使用Python实现的简单脚本,该脚本可以批量将Excel文件(.xlsx)转换为CSV文件。脚本首先遍历指定目录下的所有.xlsx文件,并逐个加载这些文件。然后,针对每个工作簿中的每张工作表,脚本读取所有单元格的数据,并将其写入到一个新的CSV文件中。CSV文件名由原始Excel文件名和工作表名组合而成。
import openpyxl,csv,os
os.chdir('C:\\Users\\Administrator\\Python35-32\\test\\excelToCSV')
for excelFile in os.listdir('.'):
  if not excelFile.endswith('.xlsx'): 
    continue
  wb = openpyxl.load_workbook(excelFile)
  wbname = excelFile.strip('.xlsx')
# 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)
    csvName = (wbname + '_' + sheetName +'.csv')
# Create the CSV filename from the Excel filename and sheet title.
    csvFileObj = open(os.path.join(csvName), 'w', newline='')
# Create the csv.writer object for this CSV file.
    csvWriter = csv.writer(csvFileObj)
# 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.
          excData = sheet.cell(row=rowNum, column=colNum).value
          rowData.append(excData)
      #print(colData)
      csvWriter.writerow(rowData)
# Write the rowData list to the CSV file.
    csvFileObj.close()

 

转载于:https://www.cnblogs.com/flying-wyf/p/6884965.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值