Below code is for extracting the Oracle data into xlsx format using Python, Code run successfully but when i opened the xlsx file giving error:
"file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."
What should i change in below code to get the data without excel crash.
import xlsxwriter
from xlsxwriter import Workbook
import cx_Oracle
import datetime
from datetime import date
dsn_tns = cx_Oracle.makedsn('HOST', 'port', sid='sid')
conn = cx_Oracle.connect(user=r'username', password='password', dsn=dsn_tns)
cursor = conn.cursor()
xlsx_file = open("path.xlsx", "w")
writer = xlsxwriter.Workbook("path.xlsx")
worksheet = writer.add_worksheet()
sql ='''
SELECT *
FROM ( SELECT STRGUID,ACTIVITYUSERID,ACTIVITYSESSIONID,ACTIVITYCODE,SERVERNAME,APPNAME,STARTTIME,ENDTIME,STRDESCRIPTION,
(To_Date('12/30/1899', 'MM/DD/YYYY HH24:MI:SS')+ STARTTIME)Decoded_Date
FROM tablename
)SUB
WHERE SUB.Decoded_Date between to_date('26-APR-2020', 'DD-MON-YYYY')
and to_date('26-JUN-2020', 'DD-MON-YYYY')
'''
cursor.execute(sql)
for r, row in enumerate(cursor.fetchall()):
for c, col in enumerate(row):
worksheet.write(r, c, col)
cursor.close()
conn.close()
xlsx_file.close()
I tried below code and working successfully for exporting the data from oracle into xlsx format using python:
import xlsxwriter
from xlsxwriter import Workbook
import cx_Oracle
import datetime
from datetime import date
import os
import logging
import sys
import getopt
import traceback
## Define Function
def writeToExcel(cur_sor):
workbook = xlsxwriter.Workbook('path.xlsx')
worksheet = workbook.add_worksheet("DATA") #Add a New Worksheet Name -
for row, row1 in enumerate(cur_sor.fetchall()):
for col, col1 in enumerate(row1):
worksheet.write(row, col, col1)
workbook.close()
def setSqlCommand():
sqlCommand = '''
SELECT *
FROM
( SELECT LROWNUM,DTIMESTAMP,LSCENARIO,LYEAR,LPERIOD,
LENTITY,LPARENT,LVALUE,LACCOUNT,LICP,LCUSTOM1,
LCUSTOM2,STRUSERNAME,STRSERVERNAME,
LACTIVITY,DDATAVALUE,BNODATA,
To_Date('12/30/1899','MM/DD/YYYY') +
DTIMESTAMP as Decoded_Date
FROM tablename
) SUB
WHERE SUB.Decoded_Date
<= to_date('28-JUN-2020', 'DD-MON-YYYY')
'''
return sqlCommand
# Function to Execute Sql commands over TNS
def runSqlTNS (sqlCommand, username, password , hostName, portNumber, sID):
dsn_tns = cx_Oracle.makedsn('HOST', 'PORT', sid='SERVICEID')
db = cx_Oracle.connect(user=r'USERNAME', password='PASSWORD', dsn=dsn_tns)
cursor = db.cursor()
cursor.execute(sqlCommand)
return cursor
def main(argv=None):
#Setup Logging Information
logging.basicConfig(filename='PATH/myapp.log', level=logging.INFO, format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.info('Started')
username = 'USERNAME'
password = 'PASSWORD'
#Define dsn entries to create a tns connection
hostName = 'HOST'
portNumber = 'PORT'
sid = 'SERVICEID'
#
try:
sqlCommand = setSqlCommand()
except Exception as e:
logging.info('Function - sqlCommand - In Exception')
logging.info(traceback.print_exc())
try:
c = runSqlTNS(sqlCommand, username, password , hostName, portNumber, sid)
except Exception as e:
logging.info('Function - runSql In Exception')
logging.info(traceback.print_exc())
try:
writeToExcel(c) # Send the Cursor to writetoExcel Function
c.close()
except Exception as e:
logging.info('Function - writeToExcel In Exception')
logging.info(traceback.print_exc())
if __name__ == "__main__":
main(sys.argv)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.