[英]How to import multiple csv files based on a list, and append them into multiple worksheets
I have multiple CSV files to be imported into multiple worksheets named in the same as the CSV file.我有多个 CSV 文件要导入到与 CSV 文件同名的多个工作表中。
However, I have difficulties in creating/appending multiple worksheets.但是,我在创建/附加多个工作表时遇到困难。
If I use ExcelWriter(pathDestination, mode = 'a')
, FileNotFoundError
happens.如果我使用
ExcelWriter(pathDestination, mode = 'a')
,则会发生FileNotFoundError
。 If I use ExcelWriter(pathDestination)
, then only the last CSV file will be created in the worksheet.如果我使用
ExcelWriter(pathDestination)
,那么工作表中只会创建最后一个 CSV 文件。
How shall I improve the code without the need of listing down each csvpath
when doing the to_excel
?在执行
to_excel
csvpath
import openpyxl
import numpy as np
import pandas as pd
import os
pathDestination = 'Downloads/TemplateOne.xlsx'
csvpathI = '2019_27101220_Export.csv'
csvpathII = '2019_27101220_Import.csv'
csvpathIII = '2020_27101220_Export.csv'
csvpathIV = '2020_27101220_Import.csv'
csvpath_list = [csvpathI, csvpathII, csvpathIII, csvpathIV]
for csvpath in csvpath_list:
df = pd.read_csv(csvpath)
conversion_unit = 1000
supplymentry_conversion_unit = 1000
df['quantity_converted'] = np.multiply(df['Quantity'],conversion_unit)
df['supplimentry_quantity_converted'] = np.multiply(df['Supplimentary Quantity'],conversion_unit)
csvnames = os.path.basename(csvpath).split(".")[0]
with pd.ExcelWriter(pathDestination) as writer:
df.to_excel(writer, sheet_name = csvnames, index = False)`
You need to put the loop inside the context manager in order to save each ( df
) to a separate sheet.您需要将循环放在上下文管理器中,以便将每个 (
df
) 保存到单独的工作表中。
Try this:尝试这个:
conversion_unit = 1000
supplymentry_conversion_unit = 1000
with pd.ExcelWriter(pathDestination) as writer:
for csvpath in csvpath_list:
df = pd.read_csv(csvpath)
df['quantity_converted'] = df['Quantity'].mul(conversion_unit)
df['supplimentry_quantity_converted'] = df['Supplimentary Quantity'].mul(supplymentry_conversion_unit)
df.to_excel(writer, sheet_name = csvpath.split(".")[0], index = False)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.