Home > Net >  split excel file based on the number of sheets using python
split excel file based on the number of sheets using python

Time:03-30

I am writing a python script that read excel file and split it into multiple files based on the number of sheets. for that i am using xlwings package

The Problem is that when i run the script it crash and display the below error:

with xw.App(visible = False) as app: AttributeError: enter

code

from pathlib import Path
import xlwings as xw



base_dir = Path(__file__).parent
output_dir = base_dir / "output" 
output_dir.mkdir(parents=True,exist_ok=True)

excel_file = "O:/WorkFiles/test.xlsm"

with xw.App(visible=False) as app:

    wb = app.books.open(excel_file)

    for sheet in wb.sheets:
        wb_new = app.books.add()

        sheet.copy(after=wb_new.sheets[0])
        wb_new.sheets[0].delete()
        wb_new.save(f"{sheet.name}.xlsx")
        wb_new.close()

CodePudding user response:

I assume there was an error in this line:

with xw.App(visible=False) as app:

But without it, your code works. Have fun

from pathlib import Path
import xlwings as xw



base_dir = Path(__file__).parent
output_dir = base_dir / "output" 
output_dir.mkdir(parents=True,exist_ok=True)

excel_file = "O:/WorkFiles/test.xlsm"

app = xw.App(visible=False)
wb = xw.Book(excel_file)


 for sheet in wb.sheets:
     wb_new = app.books.add()
     sheet.copy(after=wb_new.sheets[0])
     wb_new.sheets[0].delete()
     wb_new.save(f"{sheet.name}.xlsx")
     wb_new.close()
  • Related