【问题标题】:How to write Excel formula in cells in python如何在python的单元格中编写Excel公式
【发布时间】:2020-02-11 00:25:13
【问题描述】:

我尝试在循环中的某些列中添加 Excel 公式。 简而言之:我有一个 excel 电子表格,其中由于循环,我在前 2 个列(A 和 B)中成功生成了 3000 行的随机数。 现在我想在 C 列中写出将 A 与 B 相乘的公式,并在 D 列中写出在同一个循环中 A + C 的加法。 非常感谢您提前提供的帮助!

import xlsxwriter
import os
import random


path = r"/Users/MAC/Desktop/test.xlsx"
workbook = xlsxwriter.Workbook(path)
worksheet = workbook.add_worksheet("formula")
worksheet.write(0, 0, "Amount")
worksheet.write(0, 1, "Interest")
worksheet.write(0, 2, "Fees")
worksheet.write(0, 3, "Total Amount")

for n in range(1, 3000):
    worksheet.write(n, 0, random.randint(1,150000))
    worksheet.write(n, 1, random.randint(1, 100))
    # worksheet.write(n,2, a*b/100) ??????
    # worksheet.write(n,3, a+c) ??????
workbook.close()

【问题讨论】:

  • 到底是什么问题?你在哪个部分苦苦挣扎?你做过研究吗?

标签: python excel formula cell


【解决方案1】:

您可以使用worksheet.write_formula
示例:

for n in range(1, 10):
    worksheet.write(n, 0, random.randint(1,150000))
    worksheet.write(n, 1, random.randint(1, 100))
    cell1 = xl_rowcol_to_cell(n,0)
    cell2 = xl_rowcol_to_cell(n,1)
    worksheet.write_formula(n, 2, f'=({cell1}*{cell2})/100')
workbook.close()

xl_rowcol_to_cell 将单元格从坐标转换为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2018-12-19
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多