简体   繁体   English

使用xlsxwriter 将pandas df 写入excel 文件?

[英]Write pandas df into excel file with xlsxwriter?

I have scripted code for writing pandas df into excel file with openpyxl.我已经编写了用于使用 openpyxl 将 pandas df 写入 excel 文件的脚本代码。 See Fill in pd data frame into existing excel sheet (using openpyxl v2.3.2) .请参阅将 pd 数据框填充到现有的 excel 表中(使用 openpyxl v2.3.2)

from openpyxl import load_workbook
import pandas as pd
import numpy as np

book=load_workbook("excel_proc.xlsx")
writer=pd.ExcelWriter("excel_proc.xlsx", engine="openpyxl")
writer.book = book
writer.sheets = dict((ws.title, ws) for ws in book.worksheets)
data_df.to_excel(writer, sheet_name="example", startrow=100, startcol=5, index=False)
writer.save()

That procedure works fine.该程序工作正常。 However, each returned excel file reports, when opening, that it is corrupted, since content is not readable.但是,每个返回的 excel 文件在打开时都会报告它已损坏,因为内容不可读。 Excel can repair it and save it again. Excel 可以修复它并再次保存它。 But this has to be done manually.但这必须手动完成。 Since I have to process many files, how can i solve/circumvent that?由于我必须处理许多文件,我该如何解决/规避它?

Alternatively, how do I have to change the code to use "xlsxwriter" instead of "openpyxyl"?或者,我如何更改代码以使用“xlsxwriter”而不是“openpyxyl”?

When I just exchange "engine="openpyxl"" with "engine="xlsxwriter"" python tells me that "'Worksheet' object has no attribute 'write'" at the data_df.to_excel line.当我只是将“engine =“openpyxl”与“engine =“xlsxwriter””交换时,python告诉我“'Worksheet'对象在data_df.to_excel行没有属性'write'”。

Addition: Excel tells me "removed records named range of /xl/workbook.xml part" is the corruption and has to be repaired.另外:Excel 告诉我“已删除名为 /xl/workbook.xml 部分范围的记录”是损坏的,必须修复。 I do not know, what it means不知道是什么意思

I think you'll have to use openpyxl , because xlsxwriter doesn't support yet modifying of existing Excel XLSX files.我认为您必须使用openpyxl ,因为xlsxwriter尚不支持修改现有的 Excel XLSX 文件。

From docs :文档

  • It cannot read or modify existing Excel XLSX files.无法读取或修改现有的 Excel XLSX 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM