convert.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import zipfile
  2. import openpyxl
  3. import xlrd
  4. import csv
  5. import plac
  6. from pathlib import Path
  7. def convert_folder(folder=None):
  8. if folder is None:
  9. folder = str(Path(__file__).parent)
  10. for xls_file in Path(folder).absolute().glob('*.xls'):
  11. convert_old(xls_file)
  12. for xls_file in Path(folder).absolute().glob('*.xlsx'):
  13. convert(xls_file)
  14. def localize_floats(el):
  15. return str(el).replace('.', ',') if isinstance(el, float) else el
  16. def convert_old(xls_file: Path):
  17. print('\n' + str(xls_file))
  18. try:
  19. workbook = xlrd.open_workbook(xls_file, ignore_workbook_corruption=True)
  20. except xlrd.XLRDError as e:
  21. print(e)
  22. return
  23. # first sheet as master without suffix
  24. csv_file = f'{xls_file.parent}/{xls_file.stem}.csv'
  25. print('-> ' + csv_file)
  26. ws = workbook.sheet_by_index(0)
  27. with open(csv_file, 'w', encoding='latin-1') as fwh:
  28. wr = csv.writer(fwh, delimiter=';')
  29. for rownum in range(ws.nrows):
  30. wr.writerow([localize_floats(el) for el in ws.row_values(rownum)])
  31. for sheet in workbook.sheet_names():
  32. csv_file = f'{xls_file.parent}/{xls_file.stem}_{sheet}.csv'
  33. print('-> ' + csv_file)
  34. ws = workbook.sheet_by_name(sheet)
  35. with open(csv_file, 'w', encoding='latin-1') as fwh:
  36. wr = csv.writer(fwh, delimiter=';')
  37. for rownum in range(ws.nrows):
  38. wr.writerow([localize_floats(el) for el in ws.row_values(rownum)])
  39. def convert(xls_file: Path):
  40. print('\n' + str(xls_file))
  41. try:
  42. workbook = openpyxl.load_workbook(xls_file)
  43. except zipfile.BadZipFile as e:
  44. print(e)
  45. return
  46. # first sheet as master without suffix
  47. csv_file = f'{xls_file.parent}/{xls_file.stem}.csv'
  48. print('-> ' + csv_file)
  49. sheet = workbook.worksheets[0]
  50. with open(csv_file, 'w', encoding='latin-1') as fwh:
  51. wr = csv.writer(fwh, delimiter=';')
  52. for row in sheet.iter_rows():
  53. wr.writerow([localize_floats(cell.value) for cell in row])
  54. for sheet in workbook:
  55. csv_file = f'{xls_file.parent}/{xls_file.stem}_{sheet.title}.csv'
  56. print('-> ' + csv_file)
  57. with open(csv_file, 'w', encoding='latin-1') as fwh:
  58. wr = csv.writer(fwh, delimiter=';')
  59. for row in sheet.iter_rows():
  60. wr.writerow([localize_floats(cell.value) for cell in row])
  61. if __name__ == '__main__':
  62. plac.call(convert_folder)