根据Oracle查询将标题行写入Excel

我试图找出一个有效的方法,从我的Oracle表中写入一个xls文件,而不是每次都这样做,因为我的结果是50-70列。

headings1 = ['Column 1', 'Column 2', etc] rowx = 0 for colx, value in enumerate(headings1): sheet1.write(rowx,colx,value) 

我当前的代码将只写入从第2行开始的数据行,因为我已经手动创build了一个Excel文件模板,它具有预定义的所有工作表名称和标题行,但创build该模板需要很多工作,而且我想要获取摆脱那部分,并自动将第1行作为我的标题。

 Import CX_Oracle Import xlwt Import xlutils.copy Import xlrd SQL = "SELECT Column1, Column2, etc from TABLE" cursor = con.cursor() cursor.execute(SQL) wb_read = xlrd.open_workbook('Template.xls',formatting_info=True) wb_read.Visible = 1 wb_write = copy(wb_read) sheet0 = wb_write.get_sheet(0) for i, row in enumerate(cursor): for j, col in enumerate(row): sheet1.write(i+1,j,col) #Starts pasting the data at row 2 book.save('Output.xls') 

当前文件包括5-7张表格,我必须在同一个工作簿中写入数据以及使用5-7个光标,这是第一个光标的示例。

PEP 249允许在cx_Oracle中实现 游标对象的.description属性 。

这将返回一个元组列表,其中每个元组的第一个元素是列名称:

 >>> db = cx_Oracle.connect('schema/pw@db/db') >>> curs = db.cursor() >>> sql = "select * from dual" >>> curs.execute(sql) <__builtin__.OracleCursor on <cx_Oracle.Connection to schema@db/db>> >>> column_names = curs.description >>> column_names [('DUMMY', <type 'cx_Oracle.STRING'>, 1, 1, 0, 0, 1)] >>> 

为了演示一个(非常)稍微复杂的情况,我创build了这个表格:

 SQL> create table tmp_test (col1 number, col2 varchar2(10)); Table created. 

然后,你如何使用它:

 >>> sql = "select * from tmp_test" >>> curs.execute(sql) <__builtin__.OracleCursor on <cx_Oracle.Connection to schema@db/db>> >>> curs.description [('COL1', <type 'cx_Oracle.NUMBER'>, 127, 22, 0, -127, 1), ('COL2', <type 'cx_Oracle.STRING'>, 10, 1 0, 0, 0, 1)] >>> ','.join(c[0] for c in curs.description) 'COL1,COL2' >>> 

只需在开始枚举游标值之前写下这行。

我需要做同样的事情。 它用以下代码实现了:

 # Write header row for c, col in enumerate(cursor.description): ws.write(0, c, col[0]) 

然后,我使用您正在使用的simular for循环编写数据logging。