Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
export sql output to excel
#1
Hi All,

Have scenario were need to export the sql output to excel (.xls). Just wanted to check possible ways, if anything possible through python?
Kindly suggest or throw some ideas.

Regards,
Kranthi
Reply
#2
Sure. It's very easy to write a comma separated value (csv) file from Python. Check out the csv module. Excel opens csv files natively.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Hi

Thanks alot, tried looking but couldnt find. I guess I am missing something.
Can you please guide or throw some more light.

Thanks & Regards,
Kranthi
Reply
#4
(Oct-11-2018, 07:08 PM)Kranthi Wrote: tried looking but couldnt find

Her it is csv module
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
Found this which exports to xls, but not able to execute. Do let me know if anything to be changed. I have just started learning python.

## -- Create Excel file with data from an Oracle database query.

import cx_Oracle
from xlwt import Workbook, XFStyle, Borders, Font

def write_cursor_to_excel(curs, filename, sheetTitle):

## -- write_cursor_to_excel  curs: a cursor for an open connection to an oracle database
## -- filename: name of the XLS file to create sheetTitle: name of the sheet to create
## -- create style for header row - bold font, thin border below
    fnt = Font()
    fnt.bold = True
    borders = Borders()
    borders.bottom = Borders.THIN
    hdrstyle = XFStyle()
    hdrstyle.font = fnt
    hdrstyle.borders = borders
    # create a date format style for any date columns, if any
    datestyle = XFStyle()
    datestyle.num_format_str = 'DD/MM/YYYY'
    # create the workbook. (compression: try to reduce the number of repeated styles)
    wb = Workbook(style_compression=2)
    # the workbook will have just one sheet
    sh = wb.add_sheet(sheetTitle)
    # write the header line, based on the cursor description
    c = 0
    colWidth = []
    for col in curs.description:
        #col[0] is the column name
        #col[1] is the column data type
        sh.write(0, c, col[0], hdrstyle)
        colWidth.append(1) # arbitrary min cell width
        if col[1] == cx_Oracle.DATETIME:
            colWidth[-1] = len(datestyle.num_format_str)
        if colWidth[-1] < len(col[0]):
            colWidth[-1] = len(col[0])
        c += 1
    # write the songs, one to each row
    r = 1
    for song in curs:
        row = sh.row(r)
        for c in range(len(song)):
            if song[c]:
                if curs.description[c][1] == cx_Oracle.DATETIME:
                    row.write(c, song[c], datestyle)
                else:
                    if colWidth[c] < len(str(song[c])):
                        colWidth[c] = len(str(song[c]))
                    row.write(c, song[c])
        r += 1
    for c in range(len(colWidth)):
        sh.col(c).width = colWidth[c] * 350
    # freeze the header row
    sh.panes_frozen = True
    sh.vert_split_pos = 0
    sh.horz_split_pos = 1
    wb.save(filename)

def test():
    orcl = cx_Oracle.connect('scott/tiger')
    curs = orcl.cursor()
    curs.execute(""" select * from otcadm.system_parameter 
where name in ('OTC_BATCH_DATE','OTC_ONLINE_DATE','REPORT_RUN_DATE')
order by ins_timestamp desc """)
    write_cursor_to_excel(curs, 'emp.xls', 'Employees')
if __name__ == '__main__':

    test()
Reply
#6
(Oct-16-2018, 05:54 PM)Kranthi Wrote: Found this which exports to xls, but not able to execute.
This is not very descriptive... Do you get any errors. Post full traceback in error tags. What python version, OS, DB do you use?
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,086 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  export into excel, how to implement pandas into for-loop deneme2 6 2,431 Sep-01-2022, 05:44 AM
Last Post: deneme2
Question Export Python output to Excel skyline1397 1 2,019 Jun-26-2022, 05:10 AM
Last Post: skyline1397
  How to keep columns header on excel without change after export data to excel file? ahmedbarbary 0 1,150 May-03-2022, 05:46 PM
Last Post: ahmedbarbary
  HELP on Unwanted CSV Export Output | Using Selenium to Scrape soothsayerpg 0 1,263 Jun-13-2021, 12:23 PM
Last Post: soothsayerpg
  Need help with saving output into an excel file Beyondfacts 4 2,927 Mar-22-2021, 11:51 AM
Last Post: jefsummers
  Python script to summarize excel tables, then output a composite table? i'm a total n surfer349 1 2,332 Feb-05-2021, 04:37 PM
Last Post: nilamo
  How to export from Python to Excel? jpy 4 6,345 Dec-23-2020, 03:26 PM
Last Post: jpy
  Save output into a Excel Sheet with Format Table skaailet 1 2,489 Apr-17-2020, 11:56 PM
Last Post: thirteendec
  How to extract a matrix from .xml.gz file to a excel file or any other output? enyrb 0 2,048 Oct-21-2019, 01:01 PM
Last Post: enyrb

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020