一直都想做一個網頁的excel導出功能,最近抽時間研究了下,使用urllib2與BeautifulSoup及xlwt模塊實現
urllib2這個模塊之前有用過,關於BeautifulSoup模塊,可參看http://www.bkjia.com/Pythonjc/992499.html ,介紹的比較詳細。
如下是部分視圖代碼:
首先使用urlopen解析網頁數據
urlfile = urllib2.urlopen('要解析的url地址')
html = urlfile.read()
創建BeautifulSoup對象
soup = BeautifulSoup(html)
以取表格數據為例,使用findAll取所有tag name='<td>'的數據,並將其內容加到列表中。
result=[] for line in soup.findAll('td'): result.append(line.string)
接下來就是使用xlwt模塊生成excel的實現
創建excel文件
workbook = xlwt.Workbook(encoding = 'utf8') worksheet = workbook.add_sheet('My Worksheet')
向excel文件插入數據
for tag in range(0,8): worksheet.write(0, tag, label = result[tag])
將結果返回到網頁,即可在網頁生成excel
response = HttpResponse(content_type='application/msexcel') response['Content-Disposition'] = 'attachment; filename=example.xls' workbook.save(response) return response