split.py 1.2 KB

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