Excel 到 CSV 的转换程序

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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值