简体   繁体   中英

how to save the new excel with the same style in every cell using openpyxl

I have one big excel,including several sheets. Now I need to save every sheet in one excel. Now, I finish and some cells which have formulas have value in the new excel. But I find one new problem,how can I save every sheets which keeps the original style (format) such as red background?I checked the former question, but still get no answer. Editing workbooks with rich text in openpyxl

from openpyxl import load_workbook,Workbook
wb = load_workbook("test11.xlsx",data_only=True)
sheetnames = wb.sheetnames
for name in sheetnames:
    ws = wb.get_sheet_by_name(name)
    print(ws)
    wb2 = Workbook()
    ws2 = wb2.active
    for i,row in enumerate(ws.iter_rows()):
        for j,cell in enumerate(row):
            ws2.cell(row=i+1, column=j+1, value=cell.value)
            ws2.title = name
    wb2.save(name + ".xlsx")

Every cell in openpyxl has a .style attribute that you can call and set. Your code would be this:

from openpyxl import load_workbook,Workbook
wb = load_workbook("test11.xlsx",data_only=True)
sheetnames = wb.sheetnames
for name in sheetnames:
    ws = wb.get_sheet_by_name(name)
    print(ws)
    wb2 = Workbook()
    ws2 = wb2.active
    for i,row in enumerate(ws.iter_rows()):
        for j,cell in enumerate(row):
            c = ws2.cell(row=i+1, column=j+1, value=cell.value)
            c.style = cell.style
            ws2.title = name
    wb2.save(name + ".xlsx")

You could consider the following option instead. Basically this code makes a copy of the original xlsx file and deletes the unwanted sheets before saving with the sheet name. Since it is a copy of the original it should retain all the styling etc of each sheet.

from openpyxl import load_workbook


sheetnames = load_workbook('test11.xlsx').sheetnames

for name in sheetnames:
    wb = load_workbook("test11.xlsx")
    print(wb[name])

    for delsheet in sheetnames:
        if delsheet != name:
            del wb[delsheet]

    wb.calculation.calcMode = 'auto' # set formula calculation to auto
    wb.save(name + ".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.

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