问题
I am trying to combine multiple csv files into one excel file whereby each file is it’s own sheet in the xls file.
Below is a python script that can convert all csv files in a folder into there respective excel files.
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
"""with open('output.csv', "rt", encoding = 'UTF-8') as fin:
with open('outputconvert.csv', "wt", encoding = 'UTF-8') as fout:
for line in fin:
fout.write(line.replace(';',','))"""
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
worksheet = workbook.add_worksheet('testws')
with open(csvfile, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
It works fine, but is there a way I can expand it such that it can merge files into one file and each file is in a separate worksheet
Thanks in advance
回答1:
The parameter sheet_name is constant. To export to multiple worksheets, you need to specify a different name for each worksheet. This is the tested solution:
workbook = Workbook('../your_path/joined.xlsx')
counter = 0
for csv_file in glob.glob(os.path.join('../your_path/', '*.csv')):
sheet_name = 'Sheet_' + str(counter)
counter += 1
worksheet = workbook.add_worksheet(sheet_name)
with open(csv_file, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
回答2:
Create dataframe for each csv file and copy it in one excel as individual sheet.
Please refer below link.
https://xlsxwriter.readthedocs.io/example_pandas_multiple.html
回答3:
You are creating discrete xlxs files by doing this;
for csvfile in glob.glob(os.path.join('.', '*.csv')):
workbook = Workbook(csvfile[:-4] + '.xlsx')
Instead, you should create your file(Workbook object) outside of the for loop, just for once, and then create new sheet in the loop.
This should work
import os
import glob
import csv
from xlsxwriter.workbook import Workbook
"""with open('output.csv', "rt", encoding = 'UTF-8') as fin:
with open('outputconvert.csv', "wt", encoding = 'UTF-8') as fout:
for line in fin:
fout.write(line.replace(';',','))"""
workbook = Workbook('name_your_file.xlsx')
for csvfile in glob.glob(os.path.join('.', '*.csv')):
worksheet = workbook.add_worksheet('testws')
with open(csvfile, 'rt', encoding='utf8') as f:
reader = csv.reader(f)
for r, row in enumerate(reader):
for c, col in enumerate(row):
worksheet.write(r, c, col)
workbook.close()
来源:https://stackoverflow.com/questions/57303984/how-do-i-combine-multiple-csv-files-into-one-excel-files-with-different-sheets-u