How to append to an existing excel sheet with XLWT in Python

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 00:47:36

问题


I have created an excel sheet using XLWT plugin using Python. Now, I need to re-open the excel sheet and append new sheets / columns to the existing excel sheet. Is it possible by Python to do this?


回答1:


After investigation today, (2014-2-18) I cannot see a way to read in a XLS file using xlwt. You can only write from fresh. I think it is better to use openpyxl. Here is a simple example:

from openpyxl import Workbook, load_workbook

wb = Workbook()
ws = wb.create_sheet()
ws.title = 'Pi'
ws.cell('F5').value = 3.14156265
wb.save(filename=r'C:\book2.xls')

# Re-opening the file:
wb_re_read = load_workbook(filename=r'C:\book2.xls')
sheet = wb_re_read.get_sheet_by_name('Pi')
print sheet.cell('F5').value

See other examples here: http://pythonhosted.org/openpyxl/usage.html (where this modified example is taken from)




回答2:


You read in the file using xlrd, and then 'copy' it to an xlwt Workbook using xlutils.copy.copy().

Note that you'll need to install both xlrd and xlutils libraries.

Note also that not everything gets copied over. Things like images and print settings are not copied, for example, and have to be reset.



来源:https://stackoverflow.com/questions/21856559/how-to-append-to-an-existing-excel-sheet-with-xlwt-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!