我有一个win32com Python脚本,它将多个Excel文件组合成一个电子表格并将其另存为PDF。
现在的工作原理是输出几乎全是#NAME?
,因为在计算Excel文件的内容之前输出文件(可能需要一分钟)。
我如何强制工作簿计算值并等到它完成后再继续?
excel = win32.Dispatch('Excel.Application')
# moving stuff to this spreadsheet
wb1 = excel.Workbooks.Open(filepath1)
ws1 = excel.ActiveSheet
# from this spreadsheet
wb2 = excel.Workbooks.Open(filepath2)
ws2 = excel.ActiveSheet
# supposedly this should do it, but I haven't seen results
ws1.EnableCalculation = True
ws2.EnableCalculation = True
ws1.Calculate
ws2.Calculate
wb1.Cells(2, 4).Value = wb2.Cells(1,1).Value # doing stuff with values
# right here I need it to wait and calculate everything
# so when I export it, I see the values, not the formula or "#NAME?"
wb1.Save()
ws1.ExportAsFixedFormat(0, r'C:\filename.pdf')
wb1.Close(True)
wb2.Close(True)
excel.Application(Quit)
我做过的一种愚蠢的事情,它实际上对细胞起作用,但不适用于图形 是通过整个工作表设置工作表的值自己,所以 公式被数值覆盖。
但是,图表仍未更新为其值。
range = ws1.UsedRange
num_rows = range.Row + range.Rows.Count - 1
num_cols = range.Column + range.Columns.Count - 1
for i in range(1, num_rows ):
for j in range(1, num_cols ):
ws1.Cells(i, j).Value = ws1.Cells(i, j).Value
答案 0 :(得分:0)
您必须小心使用()语法调用函数:
ws1.Calculate()
ws2.Calculate()
这将计算两个工作表的所有单元格。看来每个函数只有在完成所有计算后才会返回,这就是你想要的效果,所以除非我误解你的问题,修复就足够了。
答案 1 :(得分:0)
根据我上面的评论:
问题最终变成了别的东西,我在这里回答:https://stackoverflow.com/a/25495515/2374028
如果您使用任何类型的脚本语言,包括python的win32com,它不会自动包含加载项,并且我的计算使用了加载项,所以它只是跳过它们。