xls_read.py

Sample

Read the spreadsheet created by xls_write.py.

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