Python Excel模板读取和重写,维护公式和格式

我已经运行了色域,似乎无法find我正在寻找的东西。 我在这里find的所有线程都以死胡同而告终。 xlrd,xlwt和xlutils几乎可以做我所需要的,但是…基本的想法是,我需要使用Python将简单的数据(string)写入Excel模板的特定工作表,并将该模板写出到一个新的.xls文件。

读取模板,将其复制到一个新的工作簿对象,写入新的值,并写出新的.xls文件是没有问题的。 但是,我无法find一个维护公式和格式的Python Excel模块。

`

our = 'template.xls' # open up read-only template with formatting maintained rb = open_workbook(our,formatting_info=True) r_sheet = rb.sheet_by_index(4) # copy this to a new workbook object wb = copy(rb) # 5th sheet (index = 4) is where we need to drop the data we have w_sheet = wb.get_sheet(4) # populate with new data! for row_index in range(0, r_sheet.nrows): w_sheet.write(row_index, 1, "some string that is our data") # write it! wb.save('new.xls') 

`

在模板中阅读时,格式是保持不变的(对于某些颜色稍微改变; meh!),但公式不是,所以“new.xls”在公式曾经的地方有空白。

任何想法如何保持格式和公式?

请注意,我被locking到Python 2.7。

你可以使用openpyxl – 它只支持xlsx(和相关的格式),而不支持xls(旧的Excel格式)。

https://pypi.python.org/pypi/openpyxl/

http://openpyxl.readthedocs.org/en/latest/

https://bitbucket.org/openpyxl/openpyxl/src/2.2/doc/source/index.rst

当您打开/保存Excel工作表时,此包会保留公式。 它也保留格式,但有一些小问题。 尽pipe如此,来自原始Excel文件的图像不会被保留。

其他很酷的function包括支持条件格式,图表,迷你图等等。