简体   繁体   中英

How to put a value to an excel cell?

You'll probably laugh at me, but I am sitting on this for two weeks. I'm using python with pandas.

All I want to do, is to put a calculated value in a pre-existing excel file to a specific cell without changing the rest of the file. That's it.

Openpyxl makes my file unusable (means, I can not open because it's "corrupted" or something) or it plainly delets the whole content of the file. Xlsxwriter cannot read or modify pre-existing files. So it has to be pandas.

And for some reason I can't use worksheet = writer.sheets['Sheet1'] , because that leads to an "unhandled exception".

Guys. Help.

I tried a bunch of packages but (for a lot of reasons) I ended up using xlwings . You can do pretty much anything with it in python that you can do in Excel.

Documentation link

So with xlwings you'd have:

import xlwings as xw
# open app_excel
app_excel = xw.App(visible = False)
# open excel template
wbk = xw.Book( r'stuff.xlsx' )
# write to a cell
wbk.sheets['Sheet1'].range('B5').value = 15

# save in the same place with the same name or not
wbk.save()
wbk.save( r'things.xlsx' )

# kill the app_excel
app_excel.kill()
del app_excel

Let me know how it goes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM