使用方法:
-页面中引入jquery和jquery.table2excel.js文件。
<script type="text/javascript" src="js/jquery.min.js">script>
<script type="text/javascript" src="js/jquery.table2excel.js">script>
-HTML代码结构
<table id="table-excel">
<thead>
<tr class="noExl">
<td>class为noExl的不会被导出到exceltd>
<td>class为noExl的不会被导出到exceltd>
tr>
<tr>
<td>111111111td>
<td>111111111td>
tr>
thead>
<tbody>
<tr>
<td>222222222td>
<td>222222222td>
tr>
<tr>
<td>333333333td>
<td>333333333td>
tr>
<tr>
<td>444444444td>
<td>444444444td>
tr>
tbody>
<tfoot>
<tr><td colspan="2">合并单元格td>tr>
tfoot>
table>
-初始化插件
$("#table-excel").table2excel({
exclude:".noExl", //不被导出的表格行的CSS class类
name:"Excel Name", //导出的excel文档名称
filename:"myExcelTable" //excel文件的名称
})
table2excel插件的可用配置参数:
-首先要导入xlwt和stingIO
import xlwt
import StringIO
-创建excel文件
workbook = xlwt.Workbook(encoding = 'utf8')
worksheet = workbook.add_sheet('My Worksheet')
-向excel中插入数据
worksheet.write(0,0,"应用名称")
worksheet.write(0,0,"应用ID")
如果想给不同的行或列添加样式,即
style = xlwt.easyxf('pattern: pattern solid, fore_color 0x16; font: bold on;borders:top thin;borders:left thin;borders:right thin;borders:bottom thin;')
worksheet.write(0,0,"应用名称",style)
-将结果返回到网页
sio=StringIO.StringIO()
workbook.save(sio) #这点很重要,传给 save 函数的不是保存文件名,而是一个 StringIO 流
response.write(sio.getvalue())
return response
-解决文件名乱码和IE不能下载的问题
fname = 'testfile.xls'
agent=request.META.get('HTTP_USER_AGENT')
if agent and re.search('MSIE',agent):
response =HttpResponse(mimetype="application/vnd.ms-excel") #解决ie不能下载的问题
response['Content-Disposition'] ='attachment; filename=%s' % urlquote(fname) #解决文件名乱码/不显示的问题
else:
response =HttpResponse(mimetype="application/ms-excel")#解决ie不能下载的问题
response['Content-Disposition'] ='attachment; filename=%s' % urlquote(fname) #解决文件乱码/不显示问题
-代码整理
import xlwt
import StringIO
fname = 'testfile.xls'
agent=request.META.get('HTTP_USER_AGENT')
if agent and re.search('MSIE',agent):
response =HttpResponse(mimetype="application/vnd.ms-excel") #解决ie不能下载的问题
response['Content-Disposition'] ='attachment; filename=%s' % urlquote(fname) #解决文件名乱码/不显示的问题
else:
response =HttpResponse(mimetype="application/ms-excel")#解决ie不能下载的问题
response['Content-Disposition'] ='attachment; filename=%s' % urlquote(fname) #解决文件乱码/不显示问题
workbook = xlwt.Workbook(encoding = 'utf8')
worksheet = workbook.add_sheet('My Worksheet')
style = xlwt.easyxf('pattern: pattern solid, fore_color 0x16; font: bold on;borders:top thin;borders:left thin;borders:right thin;borders:bottom thin;')
worksheet.write(0,0,"应用名称",style)
sio=StringIO.StringIO()
workbook.save(sio) #这点很重要,传给 save 函数的不是保存文件名,而是一个 StringIO 流
response.write(sio.getvalue())
return response
以上。