【问题标题】:Python: how to read the data from the oracle, and then write to ExcelPython:如何从 oracle 中读取数据,然后写入 Excel
【发布时间】:2017-10-13 05:56:33
【问题描述】:

Python:如何从oracle中读取数据,然后写入Excel,Excel部分列可以只读?

【问题讨论】:

    标签: python excel oracle


    【解决方案1】:

    安装database driver 用于连接数据库和pandas 以简化excel 写入和数据操作。

    $ pip install cx_Oracle pandas

    在你的脚本中做这样的事情:

    import cx_Oracle
    
    con = cx_Oracle.connect('user/password@dsn')
    
    data = pd.read_sql('SELECT * FROM mytable', con)
    con.close()
    
    data.head() # take a peek at data
    data.to_excel('my_oracle_table.xlsx')
    

    【讨论】:

    • 我明白了你所展示的,但我不知道如何设置Excel部分列可以只读。(我使用python2和xlrd,xlwt)
    • 您想让某些列只读还是整个工作表?
    • 我想让某些列只读,而不是整个工作表。
    • 我也会对解决方案感到好奇。您介意将其发布为答案吗?
    【解决方案2】:

    这个答案来自: Python xlwt - making a column readonly (cell protect)

    from xlwt import Workbook, Worksheet, easyxf
    # ...
    # Protect worksheet - all cells will be read-only by default
    my_worksheet.protect = True  # defaults to False
    my_worksheet.password = "something_difficult_to_guess"
    
    # Create cell styles for both read-only and editable cells
    editable = easyxf("protection: cell_locked false;")
    read_only = easyxf("")  # "cell_locked true" is default
    # Apply your new styles when writing cells
    my_worksheet.write(0, 0, "Can't touch this!", read_only)
    my_worksheet.write(2, 2, "Erase me :)", editable)
    

    【讨论】:

      【解决方案3】:

      感谢 Robin Nemeth 的回答。我对其进行了一些修改,得到了所需的输出。

      import cx_Oracle
      con = cx_Oracle.connect('user/password@dsn')
      data = pd.read_sql('SELECT * FROM mytable', con)
      data.to_excel('my_oracle_table.xlsx')  #called before closing the connection
      con.close()
      

      这里,data.to_excel() 应该在关闭连接之前调用,否则会导致如下错误“DatabaseError: DPI-1040: LOB was already closed”。

      甚至删除了 data.head() 函数,这并没有影响我的输出。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-25
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多