如何将文件夹中的所有.csv文件转换为具有多个工作表标签(每个.csv 1个)的单个.xlsx文件? [英] How can I convert all .csv files in a folder into a single .xlsx file with multiple worksheet tabs (1 for each .csv)?
问题描述
我有一个包含20个左右.csv文件的文件夹.我想用多个工作表标签(每个.csv 1个)创建一个.xlsx文件(excel文件).
I have a folder with 20 or so .csv files. I want to create a single .xlsx file (excel file) with multiple worksheet tabs (1 for each .csv).
有人可以推荐一个简单的脚本来执行此操作,而用户只需要指定两件事即可:带有.csv文件的文件夹&新的.xlsx文件的路径?
Can somebody recommend a simple script to do this where the user only needs to specify 2 things: the folder with the .csv files & the path to the new .xlsx file?
我在此线程中发现了相同的问题,但没有答案,我可以理解:
I found the same question at this thread but without an answer I could understand:
谢谢,
推荐答案
以下代码将文件夹名称(包含多个csv文件)作为输入,并创建输出为具有多个工作表的单个xls文件
The following code takes folder name (with multiple csv files) as input and creates output as a single xls file with multiple sheets
import xlwt, csv, os
csv_folder = "Output/"
book = xlwt.Workbook()
for fil in os.listdir(csv_folder):
sheet = book.add_sheet(fil[:-4])
with open(csv_folder + fil) as filname:
reader = csv.reader(filname)
i = 0
for row in reader:
for j, each in enumerate(row):
sheet.write(i, j, each)
i += 1
book.save("Output.xls")
这篇关于如何将文件夹中的所有.csv文件转换为具有多个工作表标签(每个.csv 1个)的单个.xlsx文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!