2016-12-02 984 views
1

我想要做的是1)在excel中获得一个folmula结果和2)将值更新到现有的excel文件。 [output_result我使用“xlsxwriter”创建并编写了这个folmula。但是,当我尝试使用openpyxl(或熊猫)来检索folmula结果时,它返回0.我想用“xlwings”来解决这个问题,但不知道如何去做。谁能帮忙?如何使用xlwings获得公式结果excel

#openpyx 
wb = openpyxl.load_workbook(filename=xlsx_name,data_only=True) 
ws = wb.get_sheet_by_name("sheet1") 
print "venn_value",(ws.cell('X2').value) 
#pandas 
fold_merge_data=pd.read_excel(xlsx_name,sheetname=1) 
print fold_merge_data['Venn diagram'][:10] 
+0

该XlsxWriter公式为0时解释原因在文档中:[XlsxWriter公式结果](https://xlsxwriter.readthedocs.io/working_with_formulas.html#formula-results)。 – jmcnamara

+0

其实我之前读过文档,而且我也在另一个线程中看过xlwings可能有助于解决这个问题; [LINK1](http://stackoverflow.com/questions/38915228/fails-to-read-the-value-of-formular-after-using-xlsxwriter-to-close-and-then-usi/38922683#38922683)和[link2](http://stackoverflow.com/questions/28517508/read-excel-cell-value-and-not-the-formula-computing-it-openpyxl)。我只是想知道使用xlwings(或其他)的代码片段能够解决这个问题。 – talktalk

+0

如果您已经在使用XlsxWriter,为什么还要打扰xlwings?这些文档还向您展示了如何将值写入单元格(以及公式),以便它不为零。 –

回答

0

是,xlwings可以,因为它使用pywin32对象互动使用Excel,而不是像openpyxl和熊猫只是读/写XLSX或CSV文件,解决这个问题你。这样,Excel实际上执行公式,xlwings抓取结果。

为了获得价值,你可以这样做:

import xlwings as xw 
sheet = xw.sheets.active # if the document is open 
#otherwise use sheet = xw.Book(r'C:/path/to/file.xlsx').sheets['sheetname'] 
result = sheet['X2'].value 

另外请注意,您可以设置使用公式,例如

sheet['A1'].value = '=1+1' # or ='B1*2' if you want to reference other cells 
+0

需要注意的一件重要的事情是,这样做会打开Excel,所以基于xlwings的脚本将不能在Linux系统上运行(可能通过Wine,我没有尝试过)。而且,这种方法比通过例如大熊猫,所以如果你想处理大量的文件,它不是可扩展的。 – sheridp

+0

一个耻辱,我需要在Linux中这样的东西。 – 2017-11-04 05:18:08