0

I read and processed a sheet in an excel workbook with multiple sheets like so:

xls = pd.ExcelFile(r'C:\Users\file.xlsx')
enq = pd.read_excel(xls, 'Enq Data')

How do I export the workbook to excel after I am done with the enq sheet? I want the workbook to contain the changes made on the enq sheet? I tried exporting "xls" to_excel but that obviously didn't work

otejiri
  • 1,017
  • 6
  • 20

1 Answers1

0

It comes down to what the workbook contains (AFAIK some fancy excel stuff may not be possible to preserve).

If it is only data, then you can use probably any method, even pandas can somewhat handle it by loading the whole workbook and writing all the data into a file.

data = pd.read_excel('data.xlsx', sheetname=None)
writer = pd.ExcelWriter('target.xlsx', engine='xlsxwriter')
for sheetname in data.keys():
    # skipp "Enq Data" if needed
    data[sheetname].to_excel(writer, sheetname=sheetname)

# new sheet with your new data
enq.to_excel(writer, sheetname="Enq Data")
writer.save()

If you explicitly need to modify the file, or if it contains other stuff then data, then, depending on what it contains, you would need to use some specialized library e.g. openpyxl.

Check following questions/answers: Modify an existing Excel file using Openpyxl in Python https://stackoverflow.com/a/28254411/9327628

Marek Schwarz
  • 578
  • 6
  • 10