xls_write.py 1.3 KB

1234567891011121314151617181920212223242526272829303132
  1. import adodbapi
  2. import datetime
  3. try:
  4. import adodbapi.is64bit as is64bit
  5. is64 = is64bit.Python()
  6. except ImportError:
  7. is64 = False # in case the user has an old version of adodbapi
  8. if is64:
  9. driver = "Microsoft.ACE.OLEDB.12.0"
  10. else:
  11. driver = "Microsoft.Jet.OLEDB.4.0"
  12. filename = 'xx.xls' # file will be created if it does not exist
  13. extended = 'Extended Properties="Excel 8.0;Readonly=False;"'
  14. constr = "Provider=%s;Data Source=%s;%s" % (driver, filename, extended)
  15. conn = adodbapi.connect(constr)
  16. with conn: # will auto commit if no errors
  17. with conn.cursor() as crsr:
  18. try: crsr.execute('drop table SheetOne')
  19. except: pass # just is case there is one already there
  20. # create the sheet and the header row and set the types for the columns
  21. crsr.execute('create table SheetOne (Name varchar, Rank varchar, SrvcNum integer, Weight float, Birth date)')
  22. sql = "INSERT INTO SheetOne (name, rank , srvcnum, weight, birth) values (?,?,?,?,?)"
  23. data = ('Mike Murphy', 'SSG', 123456789, 167.8, datetime.date(1922,12,27))
  24. crsr.execute(sql, data) # write the first row of data
  25. crsr.execute(sql, ['John Jones', 'Pvt', 987654321, 140.0, datetime.date(1921,7,4)]) # another row of data
  26. conn.close()
  27. print('Created spreadsheet=%s worksheet=%s' % (filename, 'SheetOne'))