1. 程式人生 > 其它 >python 儲存excel 檔案

python 儲存excel 檔案

1,python 將資料庫資訊到處為excel。

使用模組xlwt,配合django

def excel_export(request):
    """
    匯出excel表格
    """
    list_obj = Student.objects.all()
    if list_obj:
        # 建立工作薄
        ws = Workbook(encoding='utf-8')
        w = ws.add_sheet(u"學生表")
        w.write(0, 0, "學號")
        w.write(0, 1, u"姓名")
        w.write(0, 
2, u"性別") w.write(0, 3, u"出生日期") # 寫入資料 excel_row = 1 for obj in list_obj: data_id = obj.sno data_user = obj.sname data_sex = obj.ssex data_birthday = obj.sbirthday.strftime("%Y-%m-%d") # obj.sbirthday.strftime("%Y-%m-%d")
w.write(excel_row, 0, data_id) w.write(excel_row, 1, data_user) w.write(excel_row, 2, data_sex) w.write(excel_row, 3, data_birthday) excel_row += 1 # 方框中程式碼是儲存本地檔案使用,如不需要請刪除該程式碼 ########################### exist_file = os.path.exists("
test.xls") if exist_file: os.remove(r"test.xls") ws.save("test.xls") ############################ import io output = io.BytesIO() ws.save(output) response = HttpResponse(content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=test.xls' response.write(output.getvalue()) return response

2,直接通過前端呼叫配置介面就自動下載excel檔案了。