split.py 1008 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. import win32com.client
  2. from pathlib import Path
  3. excel_format = {".csv": 6, ".xls": 56, ".xlsx": 51}
  4. def split(file, format=None):
  5. excel_com = win32com.client.Dispatch("Excel.Application")
  6. excel_com.DisplayAlerts = False
  7. # excel_com.Visible = True
  8. filename = Path(file)
  9. path = str(filename.parent.resolve())
  10. print(filename.resolve())
  11. ext = filename.suffix if format is None else format
  12. wb = excel_com.Workbooks.Open(filename.resolve())
  13. for sh in wb.Sheets:
  14. tab_filename = f"{filename.stem}_{sh.Name}{ext}"
  15. print(" --> " + tab_filename)
  16. wb2 = excel_com.Workbooks.Add()
  17. wb.Worksheets(sh.Name).Activate()
  18. ws = excel_com.ActiveSheet
  19. ws.Copy(Before=wb2.sheets(1))
  20. wb2.sheets(2).Delete()
  21. wb2.UpdateLinks = 2
  22. wb2.SaveAs(Filename=path + "\\" + tab_filename, FileFormat=excel_format[ext])
  23. wb2.Close(True)
  24. wb.Close(True)
  25. if __name__ == "__main__":
  26. split("Excel\\Mappe1.xlsx", "csv")