如何将文件夹中的所有.csv文件转换为具有多个工作表选项卡的单个.xlsx文件(每个.csv为1)?

时间:2022-05-20 20:31:21

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

我有一个包含20个左右.csv文件的文件夹。我想创建一个包含多个工作表选项卡的单个.xlsx文件(excel文件)(每个.csv为1)。

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?

有人可以推荐一个简单的脚本,用户只需要指定两件事:带有.csv文件的文件夹和新的.xlsx文件的路径吗?

I found the same question at this thread but without an answer I could understand:

我在这个帖子中找到了同样的问题但没有答案我能理解:

https://superuser.com/questions/742454/how-to-convert-many-csv-files-into-1-xlsx-file-with-multiple-tabs?rq=1

Thanks All,

2 个解决方案

#1


5  

The following code takes folder name (with multiple csv files) as input and creates output as a single xls file with multiple sheets

以下代码将文件夹名称(具有多个csv文件)作为输入,并将输出创建为具有多个工作表的单个xls文件

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

#2


1  

I see you've tagged the question with python, but an option is using the Power Query ( free Excel add-in from Microsoft ) that has a "Get External Data" -> "From Folder" option.

我看到你用python标记了这个问题,但是一个选项是使用Power Query(来自Microsoft的免费Excel加载项),它具有“获取外部数据” - >“从文件夹”选项。

#1


5  

The following code takes folder name (with multiple csv files) as input and creates output as a single xls file with multiple sheets

以下代码将文件夹名称(具有多个csv文件)作为输入,并将输出创建为具有多个工作表的单个xls文件

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

#2


1  

I see you've tagged the question with python, but an option is using the Power Query ( free Excel add-in from Microsoft ) that has a "Get External Data" -> "From Folder" option.

我看到你用python标记了这个问题,但是一个选项是使用Power Query(来自Microsoft的免费Excel加载项),它具有“获取外部数据” - >“从文件夹”选项。