0

I want to export sql query result to excel file using Python. I queried the DB and able to retrieve the result set.Currently what im facing is like.Not able write the query result to Excel, Here is my Code,

def read(db_connect):
   print("Read")
   cursor = db_connect.cursor()
   Expirydate =  date.today() + timedelta(days=90)
   print(Expirydate)
   sql_query = cursor.execute("Select StaffDetails.TypeOfEmployee, StaffDetails.EmploymentType, StaffDetails.EmploymentCategory, StaffDetails.PreferredEmpFname, StaffDetails.PreferredEmpLname, StaffDetails.Location, StaffDetails.Department, StaffDetails.Section, StaffDetails.JobTitle, StaffDetails.ContractorAgencyName, StaffDetails.SupervisorName, StaffDetails.SupervisorEmail, StaffBiodata.WorkpassType, StaffBiodata.WorkpassExpiryDate from StaffDetails INNER JOIN StaffBiodata ON StaffDetails.StaffID =StaffBiodata.StaffID WHERE Department = 'Operations' AND WorkpassExpiryDate < '%s'" % Expirydate)
   allrows = sql_query.fetchall()
   for row in allrows:
      print(f'row = {row}')
      print()
   totalrows = len(allrows)
   print("Total Rows : %d" % totalrows)
   if totalrows > 0:
       try:
           columns = [i[0] for i in cursor.description]
           
           df = pd.DataFrame(allrows)
           writer = pd.ExcelWriter(r'C:\Users\CSV\Staffdata.xlsx')
           df.to_excel(writer, sheet_name='WorkPassExpiryReport',header=True,index=False)
           writer.save()
           print(title)
           
       except:
           print("Could not write to Excel")

When im running this code,its skipping to the except block.Is there anyway to figure out the issue?

---------------------EDIT--------------------- enter image description here

----------------EDIT 2-------------------

enter image description here

Thanks, Teena

4
  • your question is too unclear. are you getting an exception? an error of some sort? do your prints not print what you expect? print(title) what is this? you don't have title defined anywhere Commented Mar 16, 2022 at 8:51
  • @Nullman print(title) is printing the column names . i am able to retrive row count and resultset of sql query. i forgot to rename title to columns,actually it is print(columns) Commented Mar 16, 2022 at 8:57
  • Does it prints Total rows? Your screenshot doesn't show it Commented Mar 16, 2022 at 9:10
  • @vovakirdan yes,its totalrows is 1 Commented Mar 16, 2022 at 9:12

1 Answer 1

1
import sqlite3 as sq
db_connect.row_factory = sq.Row # this changes  output
if totalrows > 0:
       try:
           #columns = [i[0] for i in cursor.description] i think here is an error
           #it would be better if you write columns manually
           df = pd.DataFrame(allrows, columns = sql_query.keys())
           with pd.ExcelWriter(r'C:\Users\CSV\Staffdata.xlsx') as writer:
               df.to_excel(writer, 
                           sheet_name='WorkPassExpiryReport',index=False)
           print(columns)
           
       except Exception as e:
           print("Could not write to Excel")
           print(f"Error: {str(e)}")

Try it and send screenshot

Sign up to request clarification or add additional context in comments.

8 Comments

writer.save() is outside the with statement
Sorry, my fault
@vovakirdan, thanks for the quick response.Now the error has gone, but the result is written to single column in excel .Please see the screenshot .and there is no header and my date column is displaying in different way.
I have updated answer. Try it
@vovakirdan,Hi im getting these errors File "AutomatedWorkPassExpiryReport.py", line 74, in <module> read(db_connect) File "AutomatedWorkPassExpiryReport.py", line 50, in read db_connect.row_factory = sq.Row NameError: name 'sq' is not defined Can i check sq.row is for sqllite3 module .ryt?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.