使用python导出数据时预先计算Excel公式?

时间:2016-10-25 19:51:58

标签: python excel xlsxwriter xlslib

代码拉动然后放入excel公式而不是公式的计算数据。

xxtab.write(8, 3, "=H9+I9")

当读入并存储在该单独的文件中时,它存储为“= H9 + I9”而不是H9 + I9的实际值。然后,当我们将它导回时,它仍然没有计算H9 + I9实际上是什么,而是只是将“= H9 + I9”重新粘贴到excel中。

预期目标是在导出期间,导出之后但导入到另一个文件之前或导入期间完成数学计算。

代码不应该只是将另一个数学函数/公式放入下一个Excel工作表中。它应该为正在阅读的内容提供答案。

import xlsxwriter, string, csv, time, datetime, subprocess, os
import urllib, urllib2, requests, openpyxl, sys
import gspread

# grab files
workbook = '/path/to/the/WorkBook.xlsx'

# Setup the spreadsheet
print "Creating workbook"
book = xlsxwriter.Workbook(workbook, {'strings_to_numbers': True})

# set matrix
row = 0  # row number
col = 0  # Column letter A=0 B=1 C=2 D=3...Z=26 ect.
# var.write(row, col, value, format)

# Make the sheet
xxtab = book.add_worksheet('DB Tables')

#Example of some .write commands which write to xxtab. The variables are taken directly from excel and are being read in by xlsl reader. This is stored in another file and is read in by the for loop.
xxtab.write(8, 1, "T_ACCESSRULES")
xxtab.write(8, 3, "=H9+I9")
xxtab.write(8, 7, "=data_dbmetrics!B56")

# The for loop, reads in a .txt file and does multiple .write commands
with open('/path/to/my/file/interns_xxtables.txt', 'rb') as f:
    reader = csv.reader(f, delimiter='\t')
    for c, col in enumerate(reader):
        if(len(col) > 3):
            if (str(col[3]) == "bold"):
                xxtab.write(int(col[0]), int(col[1]), col[2], bold)
            elif (col[3] == "metric"):
                xxtab.write(int(col[0]), int(col[1]), col[2], metric)
            elif (col[3] == "title"):
                xxtab.write(int(col[0]), int(col[1]), col[2], title)
        else:
            xxtab.write(int(col[0]), int(col[1]), col[2])
f.close()

抱歉,我是Stack Overflow的新手。我不确定如何描述这个问题。我不知道如何得到我想要的东西,我只知道我想要的东西是不是用我所写的东西来实现的。

1 个答案:

答案 0 :(得分:1)

  

预期的目标是在导出期间,导出之后但导入到另一个文件之前或导入期间完成数学计算。

XlsxWriter(显示写入Excel文件的模块)不会评估它写入的公式的结果。如果您在代码中计算结果,则可以在编写公式时添加它:

xxtab.write(8, 3, "=H9+I9", 42)

XlsxWriter文档的Working with Formulas部分对此进行了更详细的说明。

没有Python Excel文件编写模块评估公式。可以做到这一点的唯一模块是自动化Excel的模块,例如XlWings