xls_read.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import sys
  2. import adodbapi
  3. try:
  4. import adodbapi.is64bit as is64bit
  5. is64 = is64bit.Python()
  6. except ImportError:
  7. is64 = False
  8. if is64:
  9. driver = "Microsoft.ACE.OLEDB.12.0"
  10. else:
  11. driver = "Microsoft.Jet.OLEDB.4.0"
  12. extended = 'Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"'
  13. try: # first command line argument will be xls file name -- default to the one written by xls_write.py
  14. filename = sys.argv[1]
  15. except IndexError:
  16. filename = 'xx.xls'
  17. constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended)
  18. conn = adodbapi.connect(constr)
  19. try: # second command line argument will be worksheet name -- default to first worksheet
  20. sheet = sys.argv[2]
  21. except IndexError:
  22. # use ADO feature to get the name of the first worksheet
  23. sheet = conn.get_table_names()[0]
  24. print('Shreadsheet=%s Worksheet=%s' % (filename, sheet))
  25. print('------------------------------------------------------------')
  26. crsr = conn.cursor()
  27. sql = "SELECT * from [%s]" % sheet
  28. crsr.execute(sql)
  29. for row in crsr.fetchmany(10):
  30. print(repr(row))
  31. crsr.close()
  32. conn.close()