将行追加到 excel sheet python 的顶部

Append row to top of excel sheet python

如何在 excel sheet 的顶部追加一行?目标如下:

文件本身使用pandas.df.to_excel写成如下:

import pandas

with pandas.ExcelWriter(output_filename) as writer:
   for file in files:
      df = pandas.read_csv(file)
      df.to_excel(writer, sheet_name=file.replace(".csv", "").replace("_", " ").title(), index=False)

之后您可以使用 openpyxl 编辑您的 Excel 文件:

import contextlib

import openpyxl
import pandas as pd


new_row = "THIS ROW IS APPENDED AFTER THE FILE IS WRITTEN BY PANDAS"

with contextlib.closing(openpyxl.open(output_filename)) as wb:
    for file in files:
        sheet_name = file.replace(".csv", "").replace("_", " ").title()
        sheet = wb[sheet_name]
        sheet.insert_rows(0)
        sheet["A1"] = new_row
    wb.save(output_filename)

这是使用 XlsxWriter 作为 Excel 引擎的一种方法:

with pandas.ExcelWriter(output_filename, engine='xlsxwriter') as writer:
    for file in files:
        df = pandas.read_csv(file)
        sheet_name = file.replace(".csv", "").replace("_", " ").title()

        df.to_excel(writer, sheet_name=sheet_name, index=False, startrow=1)

        worksheet = writer.sheets[sheet_name]
        worksheet.write('A1', 'Here is some additional text')