Excel文件的建立和下載

簡述:利用xlwt和django將table內的數據轉換爲excel文件下載到本地保存python

生成Excel文件:

      使用了 xlwt 庫,xlwt庫能夠將數據和格式信息寫入到Excel文件中,具體步驟以下
      1:建立Excel文件首先須要實例化 Workbook 對象
          class   xlwt.Workbook.Workbook(encoding ='ascii',style_compression = 0 )
          有兩個參數 encoding→文件編碼格式    style_compression → 是否壓縮 ,通常狀況下使用默認參數便可。
      2:經過Workbook的add_sheet方法建立工做表
         add_sheet (sheetname, cell_overwrite_ok=False)
         sheetname→工做表名稱   cell_overwrite_ok 重複寫入同一個單元格是否覆蓋原有內容,經過源碼中發現當咱們調用這個  方法的時候實際上獲得的返回結果爲一個Worksheet實例化對象django

def add_sheet(self, sheetname, cell_overwrite_ok=False):
        """
        This method is used to create Worksheets in a Workbook.

        :param sheetname:

          The name to use for this sheet, as it will appear in the
          tabs at the bottom of the Excel application.

        :param cell_overwrite_ok:

          If ``True``, cells in the added worksheet will not raise an
          exception if written to more than once.

        :return:

          The :class:`~xlwt.Worksheet.Worksheet` that was added.

        """
        from . import Utils
        from .Worksheet import Worksheet
        if not isinstance(sheetname, unicode_type):
            sheetname = sheetname.decode(self.encoding)
        if not Utils.valid_sheet_name(sheetname):
            raise Exception("invalid worksheet name %r" % sheetname)
        lower_name = sheetname.lower()
        if lower_name in self.__worksheet_idx_from_name:
            raise Exception("duplicate worksheet name %r" % sheetname)
        self.__worksheet_idx_from_name[lower_name] = len(self.__worksheets)
        self.__worksheets.append(Worksheet(sheetname, self, cell_overwrite_ok))
        return self.__worksheets[-1]

     3:往單元格里面寫入數據
            經過Worksheet 的write方法寫入數據writer,c,label ='',style = <xlwt.Style.XFStyle object> 
            r 、c參數爲單元格的行列數  label須要寫入的數據  
            style指定單元格的內容格式 經過
xlwt.Style.easyxf()方法建立格式對象,包含字體、大小、顏色等
  4: 保存
    使用Workbook中的save方法保存,save方法提供兩種保存方式:1.寫入到本地磁盤  2.具備
write方法的流對象app

Excel文件下載

Django提供有自帶的文件下載功能,直接導入引用就能夠了字體

from django.http import FileResponse
file = open(name, 'rb')
response = FileResponse(file)
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename=' + datetime.now().strftime("%Y-%m-%d") + name
return response

示例this

import xlwt


def write(data, name):
    wbx = xlwt.Workbook()
    sheet = wbx.add_sheet('Sheet1', cell_overwrite_ok=True)
    for row, i in enumerate(data):
        col = 0
        for j in i:
            sheet.write(row, col, i[j])
            col += 1
    wbx.save(name)
相關文章
相關標籤/搜索