将列表保存到Excel文件 - 使用Python代码。
我刚开始学习Python。
我想把一个列表保存到Excel文件里。有没有人能帮我看看我的代码?
try:
sqlite_cursor.execute(query)
projects_data = sqlite_cursor.fetchall()
projects = list()
for row in projects_data:
dict_temp = dict()
dict_temp['GivenName'] = row[0]
dict_temp['surname'] = row[1]
dict_temp['DeptDesc'] = row[2]
dict_temp['Region'] = row[3]
dict_temp['LicType'] = row[4]
dict_temp['LicClass'] = row[5]
dict_temp['Licence_Number'] = row[6]
dict_temp['License_Holder_Name'] = row[7]
dict_temp['License_Description'] = row[8]
dict_temp['LicStatus'] = row[9]
dict_temp['Issue_Date'] = row[10]
dict_temp['Expiry_Date'] = row[11]
projects.append(dict_temp)
wb = Workbook() # creates a workbook object.
ws = wb.active # creates a worksheet object.
row_count = len(projects)
for row_count in projects:
ws.append(row_count) # adds values to cells, each list is a new row.
wb.save('Driver License.xlsx') # save to excel file.
except:
exit()
# Save Workbook
print('Save Workbook')
try:
wb.SaveAs(save_workbook)
except:
close_out()
exit()
1 个回答
0
首先,安装 openpyxl
这个库:
pip install openpyxl
然后,把你的代码改成这样:
from openpyxl import Workbook
try:
sqlite_cursor.execute(query)
projects_data = sqlite_cursor.fetchall()
projects = []
for row in projects_data:
dict_temp = {
'GivenName': row[0],
'surname': row[1],
'DeptDesc': row[2],
'Region': row[3],
'LicType': row[4],
'LicClass': row[5],
'Licence_Number': row[6],
'License_Holder_Name': row[7],
'License_Description': row[8],
'LicStatus': row[9],
'Issue_Date': row[10],
'Expiry_Date': row[11],
}
projects.append(dict_temp)
wb = Workbook()
ws = wb.active
for project in projects:
ws.append(project.values())
wb.save('DriverLicense.xlsx')
print('Excel file saved successfully.')
except Exception as e:
print(f'Error occurred: {e}')
# Handle the exception as needed
我之前也遇到过同样的问题,使用 openpyxl
这个库帮了我很多忙。