import xlwt 假設 網頁上有個導出 execl按鈕 點擊後 把頁面上的數據下載到execl表 def download(request): task_id = request.GET.get('task_id') wb =xlwt.Workbook(encoding='utf-8') ws = wb.add_sheet('Banned_pid_Table')#創建execl的第一個sheet n = 1 ##設置第i列 的cell單元格的寬度## for i in range(0,3): ws.col(i).width = 0x0d00 + 3000 ws.write(0, 0, '產品ID') ws.write(0, 1, '觸犯的違禁詞') ws.write(0, 2, '產品URL') sql = "select pid,banword,url from bannedword_check_result where task_id = {0} order by addtimes".format(int(task_id)) print sql mysql_status, conn = get_conn() DATA=get_sql_data(conn,sql) conn.close() print DATA for data in DATA : ws.write(n, 0, data["pid"]) ws.write(n, 1, data["banword"]) ws.write(n, 2, data["url"]) n += 1 fname = datetime.datetime.now().strftime("%Y-%m-%d") + '_Banned_pid_Table.xls' response = HttpResponse(mimetype="application/vnd.ms-excel") #解決ie不能下載的問題 response['Content-Disposition'] ='attachment; filename=%s' % urllib.unquote(fname) #解決文件名亂碼/不顯示的問題 ##保存## wb.save(response) return response