I am using openpyxl() to copy the contents of an excel to another excel.
My original excel has an empty column in it, so i am not inserting the first column value and removing the empty column to the new file.
Because of this the formulas that was being used gets messed up. Ex: Original File:
A B C D E
(empty 1 2 3 =SUM(B1:D1)
column)
New File:
A B C D
1 2 3 =SUM(B1:D1)
So because of this my calculations in D column gets changed.
My code:
ORG_EXCEL_FILE = openpyxl.load_workbook("workbook.xlsx")
ORG_EXL_SHEET_NAMES = ORG_EXCEL_FILE.sheetnames
NEW_EXCEL_FILE = openpyxl.load_workbook("TEST.xlsx")
NEW_EXCEL_FILE_WS = NEW_EXCEL_FILE.active
ORG_FILE_SHEET = ORG_EXCEL_FILE.get_sheet_by_name("Sheet1")
NEW_FILE_SHEET = NEW_EXCEL_FILE.get_sheet_by_name("Sheet1")
for i,row in enumerate(ORG_FILE_SHEET.iter_rows()):
for j,col in enumerate(row):
NEW_FILE_SHEET.cell(row=i+1,column=j+1).value = col.value
NEW_EXCEL_FILE.save("TEST.xlsx")
When I run the above code the col.value and col.interval_value both gives the cell formula.
I tried using openpyxl.load_workbook("workbook.xlsx", data_only=True) , it gives me None for cell.value and cell.internal_value.
Is there a way to get the exact column value instead of the formula or None value?
Thanks,
I believe you're only missing a "data_only=True" when you load your workbook. Without loading with data_only, you'll be pulling the formula itself as the value, rather than the output of the formula.
ORG_EXCEL_FILE = openpyxl.load_workbook("workbook.xlsx", data_only=True)
ORG_EXL_SHEET_NAMES = ORG_EXCEL_FILE.sheetnames
NEW_EXCEL_FILE = openpyxl.load_workbook("TEST.xlsx", data_only=True)
NEW_EXCEL_FILE_WS = NEW_EXCEL_FILE.active
ORG_FILE_SHEET = ORG_EXCEL_FILE.get_sheet_by_name("Sheet1")
NEW_FILE_SHEET = NEW_EXCEL_FILE.get_sheet_by_name("Sheet1")
for i,row in enumerate(ORG_FILE_SHEET.iter_rows()):
for j,col in enumerate(row):
NEW_FILE_SHEET.cell(row=i+1,column=j+1).value = col.value
NEW_EXCEL_FILE.save("TEST.xlsx")
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.