python xlsxwriter生成的表格微信打开公式显示为0解决方案

最近业务上有给客户自动生成结算表格表格的需求,结果生成之后,客户老是反馈在微信打开表格之后,里面的公式的值全都是0,使用其他专业表格软件打开又显示正常了

定位问题

    1. 微信文档查看器、表格查看器,只能对表格的值进行查看,不能对公式进行计算。
    1. xlsxwriter对表格写入公式的时候,如果不指定公式的值,xlsxwriter是不会去计算公式的值而是以默认值0填充。文档:https://xlsxwriter.readthedocs.io/working_with_formulas.html

原文:XlsxWriter doesn’t calculate the result of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened.
This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications. However, applications that don’t have a facility to calculate formulas will only display the 0 results. Examples of such applications are Excel Viewer, PDF Converters, and some mobile device applications.
If required, it is also possible to specify the calculated result of the formula using the optional value parameter for [write_formula()]:
worksheet.write_formula('A1', '=2+2', num_format, 4)(https://xlsxwriter.readthedocs.io/worksheet.html#write_formula "write_formula")

问题解析&解决方案

这是由于公式的保存的值为默认值导致的问题
解决方案也比较简单:

    1. 客户使用正经的表格软件打开就可以解决问题(因为此时表格打开后会立即重新计算一遍公式,客户看到的时候,0已经被重新计算后覆盖了。表格当时就正常了)

考虑到客户可能会觉得你技术不太行,为啥别人给他的表微信都正常,就你给的表不行?
下面是技术性解决方案:

    1. 写入公式的时候使用write_formula()函数,将表格公式的值一起写进去。

这个解决方案看起来好像有点道理,实际上有个问题:我为什么要使用公式写入到表格里面?那就是因为我不想写代码计算这些公式的值呀!

    1. 终极解决方案,打开了表格再重新保存!除了人工手段,还可以用技术操作。Windows有com接口可以调用表格软件(Excel、WPS Office)打开表格然后保存。在打开表格的时候公式就已经计算完毕。
from win32com.client import DispatchEx, Dispatch   # pip install pywin32
# 让公式有值
try:
    # Excel.Application是微软的Excel软件,WPS是KET.Application
    xl_app = DispatchEx('KET.Application')  # 加了Ex可以使用独立进程打开,不干扰当前已打开文件
    xl_app.Visible = False  # 不可见
    xl_book = xl_app.Workbooks.Open(filename)  # 打开表格文件
    xl_book.Save()  # 保存
    xl_book.Close()  # 关闭表格
    xl_app.Quit()  # 退出WPS/EXCEL
except Exception as e:
    print(f'转写文件失败:{e}')

使用第三种方案,每次打开关闭表格大概会耗时2-3秒,好处就是表格的公式正常了,也不用自己计算了,客户也满意了;缺点就是如果是Linux就会比较麻烦,打开关闭表格的时候屏幕会出现一个小窗口一闪而过。

觉得有用请点个赞,谢谢啦~

你可能感兴趣的:(python xlsxwriter生成的表格微信打开公式显示为0解决方案)