在django中导出excel文件

      今天做统计页面的时候,老美那边要求能够导出excel文件以供下载,以前没做过这东东,google了下,找到了用于处理excel名为pyExcelerator的python工具,花了一小会儿看下了pyExcelerator的samples,发现挺简单易用的.剩下的问题就是它与django的整合了.

      找了好一会儿,愣是没找到pyExcelerator用于直接生成binary流,返回给HttpResponse,只找到了WorkBook里的save方法,这样子只能将excel先写在服务器硬盘上,再读出来返回给HttpResponse,想了下这方法有点不可行...那只好自己写一个方法了...

      后来找了一篇类似修改pyExcelerator的文章(http://blog.csdn.net/kernelspirit/archive/2008/10/26/3147888.aspx)

      在WorkBook中添加savestream方法:

def savestream(self): import CompoundDoc doc = CompoundDoc.XlsDoc() return doc.savestream(self.get_biff_data()) 

    在CompoundDoc.XlsDoc中添加savestream方法:

 

CompoundDoc.XlsDoc的savestream方法: def savestream(self, stream): # 1. Align stream on 0x1000 boundary (and therefore on sector boundary) padding = '/x00' * (0x1000 - (len(stream) % 0x1000)) self.book_stream_len = len(stream) + len(padding) self.__build_directory() self.__build_sat() self.__build_header() s = "" s = s + str(self.header) s = s + str(self.packed_MSAT_1st) s = s + str(stream) s = s + str(padding) s = s + str(self.packed_MSAT_2nd) s = s + str(self.packed_SAT) s = s + str(self.dir_stream) return s 

 

    最后在django里的视图方法里添加以下几行代码即可:

 

 

wb = WorkBook(...) response = HttpResponse(wb.save_stream(),mimetype='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename=matches by input.xls' return response 

 

 

你可能感兴趣的:(Django)