简体   繁体   中英

Is it possible to copy the Excel formula of a cell instead of the value using python?

Right now I'm working on combining Excel sheets into 1 new sheet, using pandas which is working. The only problem is that the value inside the new Excel sheet are plain numbers instead of the Formulas and I would like the Formulas.

Loading file

directory = os.path.dirname(__file__)
fname = os.path.join(directory, "Reisanalyze.xlsm")
print("Loading %s..." % fname)
sheet1 = pd.read_excel(fname, sheetname="Input")
sheet2 = pd.read_excel(fname, sheetname="Alternatieven")

Write to new sheet

writer = pd.ExcelWriter('first_sheet.xlsx', engine='xlsxwriter')`**
sheet1.to_excel(writer, sheet_name='Input', merge_cells=False, startrow=0, startcol=0)
    sheet2.to_excel(writer, sheet_name='Input', merge_cells=False, startrow=0, startcol=21)

I originally tried to use the pycel project which worked until I needed to load multiple sheets, which didn't work. That's why I'm using pandas to write multiple sheets into 1 sheet.

You can use OpenPyXL. Read here

Following is the test excel file testexl.xlsx

    A       |   B
 ---------- | ------
 =SUM(B1:B2)|   1  
            |   2

Following is the test code

from openpyxl import load_workbook
import pandas as pd
wb = load_workbook(filename = 'testexl.xlsx')
sheet_names = wb.get_sheet_names()
name = sheet_names[0]
sheet_ranges = wb[name]
df = pd.DataFrame(sheet_ranges.values)
print df

Output

    0           1
0  =SUM(B1:B2)  1
1    None       2

If you want to keep excel formulas, then you will need to stop them from being formulas and then convert them back afterwards. To do this, before conversion, on your keyboard, do control/command+F then a menu should come up in the middle of the screen then click the replace tab.

In the "find What:" box type "=" and and in the "replace with:" box type ".=". Then do replace all. This will turn the formulas to text for you to copy.

Save it as a csv file

Note: I know that this will also replace = signs inside of formula. It doesn't matter, it'll go.

After you merge them, open it back up in excel, repeat but in reverse to convert them back into formulas.

This might be easier than importing extra modules.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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