将多个csv文件写入同一个excel中的不同sheet表中

pandas 的Dataframe的to_csv()会覆盖掉之前写入的表,最终导致excel中只有一个sheet

所以在这里用ExcelWriter实现写多个sheet

# coding=utf_8_sig
import pandas as pd
from openpyxl import load_workbook
import os
os.chdir('E:/pycharm/Test/profile/')
output_dir = 'E:/pycharm/Test/profile/'
def _excelAddSheet(csv_name, excelWriter, sheet_name):
    dataframe = pd.read_csv(csv_name)
    book = load_workbook(excelWriter.path)
    excelWriter.book = book
    dataframe.to_excel(excel_writer=excelWriter, sheet_name=sheet_name, index=None)
    excelWriter.close()
excelWriter = pd.ExcelWriter(os.path.join(output_dir, 'all1.xlsx'),engine='openpyxl')
pd.DataFrame().to_excel(os.path.join(output_dir, 'all1.xlsx'))
# excel必需已经存在,因此先建立一个空的sheet
list = ['app.csv','attribute.csv','city.csv','keyword.csv','profile.csv','join_uv.csv','profile_cate1.csv','star.csv']
for i in list:
    sheet_name = i[:-4]
    _excelAddSheet(i, excelWriter, sheet_name)

 

你可能感兴趣的:(python)