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,
JavaScript
x
25
25
1
def read(db_connect):
2
print("Read")
3
cursor = db_connect.cursor()
4
Expirydate = date.today() + timedelta(days=90)
5
print(Expirydate)
6
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)
7
allrows = sql_query.fetchall()
8
for row in allrows:
9
print(f'row = {row}')
10
print()
11
totalrows = len(allrows)
12
print("Total Rows : %d" % totalrows)
13
if totalrows > 0:
14
try:
15
columns = [i[0] for i in cursor.description]
16
17
df = pd.DataFrame(allrows)
18
writer = pd.ExcelWriter(r'C:UsersCSVStaffdata.xlsx')
19
df.to_excel(writer, sheet_name='WorkPassExpiryReport',header=True,index=False)
20
writer.save()
21
print(title)
22
23
except:
24
print("Could not write to Excel")
25
When im running this code,its skipping to the except block.Is there anyway to figure out the issue?
—————-EDIT 2——————-
Thanks, Teena
Advertisement
Answer
JavaScript
1
16
16
1
import sqlite3 as sq
2
db_connect.row_factory = sq.Row # this changes output
3
if totalrows > 0:
4
try:
5
#columns = [i[0] for i in cursor.description] i think here is an error
6
#it would be better if you write columns manually
7
df = pd.DataFrame(allrows, columns = sql_query.keys())
8
with pd.ExcelWriter(r'C:UsersCSVStaffdata.xlsx') as writer:
9
df.to_excel(writer,
10
sheet_name='WorkPassExpiryReport',index=False)
11
print(columns)
12
13
except Exception as e:
14
print("Could not write to Excel")
15
print(f"Error: {str(e)}")
16
Try it and send screenshot