Skip to main content
 首页 » 编程设计

python之基于 Oracle 查询将标题行写入 Excel

2024年10月25日13zhenyulu

我正在尝试找到一种有效的方法,将标题行从我的 Oracle 表写入 xls 文件,而不必每次都这样做,因为我的一些结果跨越 50-70 列。

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

我当前的代码只会写入从第 2 行开始的数据行,因为我一直在手动创建一个 Excel 文件模板,其中预定义了所有工作表名称和标题行,但是创建模板需要很多工作,而且我想要摆脱那部分并让它自动将第 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 允许 .description attribute of cursor objects , 这一直是 implemented in cx_Oracle .

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

>>> 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)] 
>>> 

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

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' 
>>> 

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