我正在尝试找出一种有效的方法,将标题行从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个游标,这是第一个游标的示例。
发布于 2015-03-23 21:26:54
PEP 249允许已经被implemented in cx_Oracle的.description attribute of cursor objects。
这将返回一个元组列表,其中每个元组的第一个元素是列名:
>>> 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'
>>>在开始枚举光标值之前,只需写下这一行。
发布于 2016-07-14 13:40:34
我需要做完全相同的事情。它是通过以下代码获得的:
# Write header row
for c, col in enumerate(cursor.description):
ws.write(0, c, col[0])然后,我使用您已经在使用的模拟for循环来编写数据记录。
https://stackoverflow.com/questions/29210241
复制相似问题