【发布时间】:2021-10-06 03:28:01
【问题描述】:
目前我想做的是从数据框列表中获取数据,并将它们作为自己的选项卡添加到现有的 excel 文件中。
为了测试这一点,我用一个数据框进行了尝试。没有错误,但是当我打开excel文件时,它说它已损坏。我继续恢复信息,但我宁愿不必每次都这样做。我相信如果我遍历我的列表来实现这一点,它会失败。
import os,glob
import pandas as pd
from openpyxl import load_workbook
master_file='combined_csv.xlsx'
#set the directory
os.chdir(r'C:\Users\test')
#set the type of file
extension = 'csv'
#take all files with the csv extension into an array
all_filenames = [i for i in glob.glob('*.{}'.format(extension))]
col_to_keep=["Name",
"Area (ft)",
"Length (ft)",
"Center (ft)",
"ID",
"SyncID"]
combine_csv = pd.concat([pd.read_csv(f, delimiter=';', usecols=col_to_keep) for f in all_filenames])
combine_csv.to_excel(master_file, index=False,sheet_name='All')
# Defining the path which excel needs to be created
# There must be a pre-existing excel sheet which can be updated
FilePath = r'C:\Users\test'
# Generating workbook
ExcelWorkbook = load_workbook(FilePath)
# Generating the writer engine
writer = pd.ExcelWriter(FilePath, engine = 'openpyxl')
# Assigning the workbook to the writer engine
writer.book = ExcelWorkbook
# Creating first dataframe
drip_file = pd.read_csv(all_filenames[0], delimiter = ';', usecols=col_to_keep)
SimpleDataFrame1=pd.DataFrame(data=drip_file)
print(SimpleDataFrame1)
# Adding the DataFrames to the excel as a new sheet
SimpleDataFrame1.to_excel(writer, sheet_name = 'Drip')
writer.save()
writer.close()
它似乎运行良好,没有错误,但是当我打开 excel 文件时,我得到如下所示的错误。
有没有人发现代码有问题会导致 excel 给我这个错误?
提前谢谢你
【问题讨论】:
标签: python excel pandas dataframe openpyxl