将查询数据导出为excel的方法有很多,我这里用了其中的一种方法,其中用到了pandas的库,其实这个库比较笨重,单纯作为excel导出的话,不做推荐。
output = BytesIO() writer = pd.ExcelWriter(output, engine='xlsxwriter') workbook = writer.book worksheet = workbook.add_worksheet('sheet1') worksheet.write('A1', u'列名') worksheet.write('B1', ) worksheet.write('C1', ) worksheet.write('D1', ) worksheet.write('E1', ) worksheet.write('F1', ) worksheet.write('G1', ) worksheet.write('H1', ) worksheet.write('I1', ) worksheet.write('J1', ) worksheet.write('K1', ) worksheet.write('L1', ) row = 1 col = 0
data = []
将数据库查询的结果放到data中
for A,B,C,D,E,F,G,H,I,J,K,L in (data): K = str(K) L = str(L) worksheet.write(row, col, A) worksheet.write(row, col + 1, B) worksheet.write(row, col + 2, C) worksheet.write(row, col + 3, float(D)/1000) worksheet.write(row, col + 4, E) worksheet.write(row, col + 5, F) worksheet.write(row, col + 6, G) worksheet.write(row, col + 7, H) worksheet.write(row, col + 8, I) worksheet.write(row, col + 9, float(J)/1000) worksheet.write(row, col + 10, K) worksheet.write(row, col + 11, L) row +=1 worksheet.set_column('A:L', 20) workbook.close() output.seek(0) return send_file(output, attachment_filename=".xlsx", as_attachment=True)