【问题标题】:Write a header row into a Excel based on an Oracle query基于 Oracle 查询将标题行写入 Excel
【发布时间】:2015-05-26 10:37:17
【问题描述】:

我正在尝试找出一种将标题行从我的 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 个游标,这是第一个游标的示例。

【问题讨论】:

    标签: python excel oracle python-2.7 cx-oracle


    【解决方案1】:

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

    在开始枚举光标值之前写下这一行。

    【讨论】:

    • 感谢 Ben 您的意见。我一直在按照您的建议研究 PEP249,但我仍然无法找出将 curs.description 放入 csv 文件第一行的每一列的正确代码。你知道怎么写吗?
    【解决方案2】:

    我需要做同样的事情。它是通过以下代码实现的:

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

    然后我使用您已经在使用的模拟 for 循环编写数据记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多