Jerry Shi
Jerry Shi

Reputation: 43

Modifying and writing data in an existing excel file using Python

I have an Excel file(xlsx) that already has lots of data in it. Now I am trying to use Python to write new data into this Excel file. I looked at xlwt, xldd, xlutils, and openpyxl, all of these modules requires you to load the data of my excel sheet, then apply changes and save to a new Excel file. Is there any way to just change the data in the existing excel sheet rather than load workbook or saving to new files?

Upvotes: 1

Views: 5898

Answers (2)

Arun Kumar Khattri
Arun Kumar Khattri

Reputation: 1628

Please check Openpyxl once again. You can load the data, do things with python, write your results in a new sheet in the same file or same sheet and save it (as everything is happening in memory).

e.g: load data

wb = openpyxl.load_workbook("file.xlsx", data_only=True)

manipulate with python

# python codes

create sheet

some_sheet = wb.create_sheet("someSheet") # by default at the end

program to write in sheet

# program to write in sheet

save file (don't forget to close the excel file if its open before saving, as it will raise "Permission Error")

wb.save("file.xlsx"

here is the link https://openpyxl.readthedocs.io/en/default/tutorial.html

Upvotes: -1

Charlie Clark
Charlie Clark

Reputation: 19497

This is not possible because XLSX files are zip archives and cannot be modified in place. In theory it might be possible to edit only a part of the archive that makes up an OOXML package but, in practice this is almost impossible because relevant data may be spread across different files.

Upvotes: 7

Related Questions