aims
Combine multiple CSV files into one Excel file, multiple sheet worksheets.
Preface
Most methods on the Internet are to merge the csv directly , and do not create separate sheets.
There are also some answers that CSV does not support merging into multiple sheets.
There are useful macro commands on the Internet. I tried it, but I can only import one sheet . Also useful python, most of them are useless.
Despite the difficulties, finally achieved the goal using the pandas library.
Start
The following code is used, two csv files with data. (2019-04-01.csv and 2019-04-02.csv)
import pandas as pd
writer = pd.ExcelWriter('test.xlsx')
data1 = pd.read_csv("2019-04-01.csv", encoding="gbk")
data2 = pd.read_csv("2019-04-02.csv", encoding="gbk")
data1.to_excel(writer,sheet_name='2019-04-01')
data2.to_excel(writer,sheet_name='2019-04-02')
writer.save()
The first step is to import the pandas library.
Then you need to use pandas.read_csv to create a dataframe for each csv .
With a dataframe, you can turn it into a table in Excel. Finally save.
The above code is to import 2019-04-01.csv and 2019-04-02.csv into the test.xlsx table, and create two sheet worksheets 2019-04-01 and 2019-04-02 for them. .
run
Open test.xlsx after running. The effect is as follows.
beautify
Although the goal has been achieved, the first column is abnormal. One more row number .
So we need to modify it to remove the row number column. The method is very simple. Add a parameter index_col=0
data1 = pd.read_csv("2019-04-01.csv", encoding="gbk",index_col=0)
data2 = pd.read_csv("2019-04-02.csv", encoding="gbk",index_col=0)
Delete the test.xlsx just now. Run it again. The effect is as follows:
Perfect solution!
supplement
In more cases, we don't want to enter file names one by one. Instead, put all the csv files to be processed in a folder . Let python automatically read these csv files, create an Excel file, and automatically import the file name as a sheet into the Excel file.
Code:
import pandas as pd
import os
newdir = 'G:\编程代码\python代码\表格\\new'
list = os.listdir(newdir) # 列出文件夹下所有的目录与文件
writer = pd.ExcelWriter('步数.xlsx')
for i in range(0,len(list)):
data = pd.read_csv(list[i],encoding="gbk", index_col=0)
data.to_excel(writer, sheet_name=list[i])
writer.save()