简体   繁体   English

将公式值从 .xlsm 文件复制到 .xlsx 文件的 Python 代码

[英]Python code to copy formula value from .xlsm file to .xlsx file

I have a few.xlsm files in a directory.我在一个目录中有几个.xlsm 文件。 I want to write a python code that creates new.xlsx files in that directory that having the same file names as the xlsm files (just xlsx instead of xlsm).我想编写一个 python 代码,在该目录中创建与 xlsm 文件具有相同文件名的 new.xlsx 文件(只是 xlsx 而不是 xlsm)。

The xlsm files have a simple formula in cell Q1. xlsm 文件在单元格 Q1 中有一个简单的公式。 It just sums a few cells.它只是总结了几个单元格。 (like Q1 is =A1+B1). (比如 Q1 就是 =A1+B1)。 I want to copy the result of the sum in Q1 of the xlsm to the corresponding xlsx file, and it should be a constant number in the xlsx file, not a formula (since the rest of the xlsx sheet is empty).我想将xlsm的Q1中求和的结果复制到对应的xlsx文件中,并且它应该是xlsx文件中的常数,而不是公式(因为xlsx表的其余部分是空的)。

All what I try to do, it doesn't copy the result as a constant number.我尝试做的所有事情,它都不会将结果复制为常数。 It copies it as a formula, and then the value in the xlsx file is wrong (since it doesn't have the rest of the data to make the calculation).它将它复制为公式,然后 xlsx 文件中的值是错误的(因为它没有其余数据来进行计算)。

Here is my python code, what should I change so it will copy the result just as a constant number?这是我的 python 代码,我应该更改什么才能将结果复制为常数?

(edit: probably in the future I'll make the formula in Q1 more complicated, and maybe copy more cells with different formulas.. so I'm looking for a solution that will copy the data itself, not a solution that makes calculations in xlsx file by using the values in xlsm files. (编辑:可能在未来我会让 Q1 中的公式更复杂,并且可能会用不同的公式复制更多的单元格..所以我正在寻找一个将复制数据本身的解决方案,而不是在中进行计算的解决方案xlsx 文件,方法是使用 xlsm 文件中的值。

Edit2: Only these specific cells are copied. Edit2:仅复制这些特定单元格。 It does not copy the whole xlsm files to the xlsx files)它不会将整个 xlsm 文件复制到 xlsx 文件)

Thanks谢谢

import os
import openpyxl

for filename in os.listdir():
    if filename.endswith('.xlsm'):
        xlsm_wb = openpyxl.load_workbook(filename)
        xlsm_sheet = xlsm_wb.active
        xlsx_wb = openpyxl.Workbook()
        xlsx_sheet = xlsx_wb.active
   
        xlsx_sheet['Q1'] = xlsm_sheet['Q1'].value
    
        xlsx_wb.save(filename[:-1] + 'x')

You could just replicate the formula in Python.您可以在 Python 中复制公式。 Ex.前任。 add in a line that says:添加一行内容:

xlsx_sheet['Q'] = xlsx_sheet['A'] + xlsx_sheet['B']

And it will replace the formulas it imported with the results of the replicated formula.它将用复制公式的结果替换它导入的公式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM