我使用python-2.7和xlsxwriter在excel表中写入。
以下是我的代码......
workbook = Workbook('D:\S_details.xlsx')
sheet = workbook.add_worksheet()
rownum = 2
colnum = 2
for a in student_result:
for r, row in enumerate(student_result):
for c, col in enumerate(row):
bold = workbook.add_format({'bold': 1})
sheet.write('A1','Student_ID',bold)
sheet.write('B1','Student_Link',bold)
sheet.write('C1','Student_Name',bold)
sheet.write('D1','Student_Qualification',bold)
sheet.write('E1','Student_Address',bold)
sheet.write('F1','Student_City',bold)
sheet.write('G1','Student_State',bold)
sheet.write('H1','Student_Country',bold)
sheet.write('I1','Student_Stream',bold)
sheet.write('J1','Student_Gender',bold)
sheet.write(r,c,col)
rownum = rownum + 1
colnum = colnum + 1
代码运行良好但是从数据库检索的第一个条目被每列的标题覆盖。
因此只有第一个条目被覆盖,其余条目完全可见。
我也在将数据写入excel表之前打印数据,但它没有显示任何错误,也没有重复记录。
任何人都可以指导我出错的地方......
欢迎任何形式的指导/帮助。
提前谢谢你:)
答案 0 :(得分:4)
代码示例存在一些问题:
for a in student_result
循环未使用。row_num
和col_num
变量已递增但未使用。enumerate()
返回0行值,该值会被标题中的A1
,B1
条目覆盖或覆盖。解决这些问题会产生以下结果:
import xlsxwriter
workbook = xlsxwriter.Workbook('S_details.xlsx')
sheet = workbook.add_worksheet()
# Generate some sample data.
student_result = []
for num in range(1, 11):
student_result.append([num] * 10)
# Make the columns wider so that the text is visible.
sheet.set_column('A:J', 20)
# Add some formatted headers.
bold = workbook.add_format({'bold': 1})
sheet.write('A1','Student_ID',bold)
sheet.write('B1','Student_Link',bold)
sheet.write('C1','Student_Name',bold)
sheet.write('D1','Student_Qualification',bold)
sheet.write('E1','Student_Address',bold)
sheet.write('F1','Student_City',bold)
sheet.write('G1','Student_State',bold)
sheet.write('H1','Student_Country',bold)
sheet.write('I1','Student_Stream',bold)
sheet.write('J1','Student_Gender',bold)
# Write the data.
for row_num, row_data in enumerate(student_result):
for col_num, col_data in enumerate(row_data):
sheet.write(row_num + 1, col_num, col_data)
workbook.close()
答案 1 :(得分:0)
您预设了rownum和colnum,但您没有在write语句中使用它们。怎么样:
sheet.write(rownum,colnum,col)
你也可能不想在col for循环中推进rownum,所以:
for a in student_result:
for r, row in enumerate(student_result):
for c, col in enumerate(row):
bold = workbook.add_format({'bold': 1})
sheet.write('A1','Student_ID',bold)
sheet.write('B1','Student_Link',bold)
sheet.write('C1','Student_Name',bold)
sheet.write('D1','Student_Qualification',bold)
sheet.write('E1','Student_Address',bold)
sheet.write('F1','Student_City',bold)
sheet.write('G1','Student_State',bold)
sheet.write('H1','Student_Country',bold)
sheet.write('I1','Student_Stream',bold)
sheet.write('J1','Student_Gender',bold)
sheet.write(rownum,colnum,col)
colnum = colnum + 1
rownum += 1