向现有 Excel 文件添加行

Adding rows to existing Excel file

我正在尝试使用以下代码将 DataFrame 添加到现有 .xlsx 文件中现有单元格下方的行中:

book = load_workbook(r"C:\path\file_name.xlsx")
writer = pd.ExcelWriter(r"C:\path\file_name.xlsx", engine='openpyxl')
writer.book = book
writer.sheets = {ws.title: ws for ws in book.worksheets}
contract_df.to_excel(writer, startrow = 10, header = False, 
sheet_name='UsrLeaseContract')
writer.save()

我设法添加了数据,但在重新打开文件时出现以下错误:

Removed Part: /xl/styles.xml part with XML error. (Styles) HRESULT 0x8000ffff Line 1, column 0. Repaired Records: Cell information from /xl/worksheets/sheet1.xml part

和详细的XML

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"> 
    <logFileName>error344800_01.xml </logFileName>
    <summary>
     Errors were detected in file 'C:path\file_name.xlsx'
    </summary>
    <removedParts><removedPart>Removed Part: /xl/styles.xml part with XML error.  (Styles) HRESULT 0x8000ffff Line 1, column 0.
    </removedPart>
</removedParts><repairedRecords><repairedRecord>Repaired Records: Cell information from /xl/worksheets/sheet1.xml part</repairedRecord>
    </repairedRecords></recoveryLog>

你试过直接用openpyxl追加数据吗? 运行 这段代码和 运行 都没有问题。另外,打开 Exel 文件时没有收到任何警告。

from openpyxl import Workbook, load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows
import pandas as pd

# list of strings
vegetables = ['potatoes', 'carrots', 'cabbage']

# Calling DataFrame constructor on list
df = pd.DataFrame(vegetables)

wb = load_workbook('file_name.xlsx')
ws = wb['UsrLeaseContract']

for r in dataframe_to_rows(df, index=True, header=True):
    ws.append(r)

wb.save('file_name.xlsx')