XlsxWriter在公式单元格上设置格式

时间:2017-02-03 19:41:17

标签: python xlsxwriter

经过长时间的努力。

如何设置我编写公式或将要编写公式的单元格的格式?

除write_formula()之外的所有其他write_()都包含格式参数。

例如:

ws.write_number(1,1,quantity, fmt)
ws.write_number(1,2,price, fmt)
# ws.write_formula("C1","=A1*B1",fmt) <-- doesn't exists
ws.write_formula("C1","=A1*B1")

2 个答案:

答案 0 :(得分:1)

这有效:

extendedprice = (quantity*price)
ws.write_formula("C1", "=A1*B1", extendedprice, fmt)

我甚至认为我可以:

ws.write_number(1,1,quantity, fmt)
if (<price has an error>):
   ws.write_number(1,2,"n/a",fmt)
   ws.write_formula("C1", "=A1*B1", "n/a", fmt)
else:
   ws.write_number(1,2,price,fmt)
   ws.write_formula("C1", "=A1*B1", (quantity*price), fmt)

答案 1 :(得分:0)

可以使用与任何其他数据类型相同的方式将格式应用于XlsxWriter:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx')
worksheet = workbook.add_worksheet()

my_format = workbook.add_format({'bold': True, 'color': 'red'})

worksheet.write(0, 0, 'Hello', my_format)
worksheet.write(1, 0, 123,     my_format)
worksheet.write(2, 0, '=1+1',  my_format)

worksheet.write('A4', 'World', my_format)
worksheet.write('A5', 456,     my_format)
worksheet.write('A6', '=2+2',  my_format)

workbook.close()

输出:

enter image description here