4

How can I append a row at the top of an excel sheet? Goal as follows: given example

The file itself is written by using pandas.df.to_excel as follows:

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)
1
  • Looking at this, you cant use XlsWriter to open and modify an existing file. See if it helps. Commented May 18, 2021 at 13:56

2 Answers 2

3

Here is one way to do it using XlsxWriter as the Excel engine:

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')

Sign up to request clarification or add additional context in comments.

Comments

1

You can use openpyxl to edit your Excel file afterwards:

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.