vba_extract.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!C:\Bitbucket\apacsys-apacsystem\VaporRecoveryMonitor\gunreport\GunHandler\venv\Scripts\python.exe
  2. ##############################################################################
  3. #
  4. # vba_extract - A simple utility to extract a vbaProject.bin binary from an
  5. # Excel 2007+ xlsm file for insertion into an XlsxWriter file.
  6. #
  7. # Copyright 2013-2019, John McNamara, jmcnamara@cpan.org
  8. #
  9. import sys
  10. from zipfile import ZipFile
  11. from zipfile import BadZipfile
  12. # The VBA project file we want to extract.
  13. vba_filename = 'vbaProject.bin'
  14. # Get the xlsm file name from the commandline.
  15. if len(sys.argv) > 1:
  16. xlsm_file = sys.argv[1]
  17. else:
  18. print("\nUtility to extract a vbaProject.bin binary from an Excel 2007+ "
  19. "xlsm macro file for insertion into an XlsxWriter file."
  20. "\n"
  21. "See: https://xlsxwriter.readthedocs.io/working_with_macros.html\n"
  22. "\n"
  23. "Usage: vba_extract file.xlsm\n")
  24. exit()
  25. try:
  26. # Open the Excel xlsm file as a zip file.
  27. xlsm_zip = ZipFile(xlsm_file, 'r')
  28. # Read the xl/vbaProject.bin file.
  29. vba_data = xlsm_zip.read('xl/' + vba_filename)
  30. # Write the vba data to a local file.
  31. vba_file = open(vba_filename, "wb")
  32. vba_file.write(vba_data)
  33. vba_file.close()
  34. except IOError as e:
  35. print("File error: %s" % str(e))
  36. exit()
  37. except KeyError as e:
  38. # Usually when there isn't a xl/vbaProject.bin member in the file.
  39. print("File error: %s" % str(e))
  40. print("File may not be an Excel xlsm macro file: '%s'" % xlsm_file)
  41. exit()
  42. except BadZipfile as e:
  43. # Usually if the file is an xls file and not an xlsm file.
  44. print("File error: %s: '%s'" % (str(e), xlsm_file))
  45. print("File may not be an Excel xlsm macro file.")
  46. exit()
  47. except Exception as e:
  48. # Catch any other exceptions.
  49. print("File error: %s" % str(e))
  50. exit()
  51. print("Extracted: %s" % vba_filename)