一直都想做一个网页的excel导出功能,最近抽时间研究了下,使用urllib2与BeautifulSoup及xlwt模块实现
urllib2这个模块之前有用过,关于BeautifulSoup模块,可参看http://www.bkjia.com/Pythonjc/992499.html ,介绍的比较详细。
如下是部分视图代码:
首先使用urlopen解析网页数据
|
1
|
urlfile = urllib2.urlopen('要解析的url地址')<br>html = urlfile.read() |
创建BeautifulSoup对象
|
1
|
soup = BeautifulSoup(html) |
以取表格数据为例,使用findAll取所有tag name='<td>'的数据,并将其内容加到列表中。
|
1
2
3
|
result=[]for line in soup.findAll('td'): result.append(line.string) |
接下来就是使用xlwt模块生成excel的实现
创建excel文件
|
1
2
|
workbook = xlwt.Workbook(encoding = 'utf8')worksheet = workbook.add_sheet('My Worksheet') |
向excel文件插入数据
|
1
2
|
for tag in range(0,8): worksheet.write(0, tag, label = result[tag]) |
将结果返回到网页,即可在网页生成excel
|
1
2
3
4
|
response = HttpResponse(content_type='application/msexcel')response['Content-Disposition'] = 'attachment; filename=example.xls'workbook.save(response)return response |