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

2022-11-28  本文已影响0人  终可见丶

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

定位问题

原文: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")

问题解析&解决方案

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

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

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

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就会比较麻烦,打开关闭表格的时候屏幕会出现一个小窗口一闪而过。

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

上一篇 下一篇

猜你喜欢

热点阅读