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