Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django/Python: Save an HTML table to Excel

I have an HTML table that I'd like to be able to export to an Excel file. I already have an option to export the table into an IQY file, but I'd prefer something that didn't allow the user to refresh the data via Excel. I just want a feature that takes a snapshot of the table at the time the user clicks the link/button.

I'd prefer it if the feature was a link/button on the HTML page that allows the user to save the query results displayed in the table. It would also be nice if the formatting from the HTML/CSS could be retained. Is there a way to do this at all? Or, something I can modify with the IQY?

I can try to provide more details if needed. Thanks in advance.

like image 410
kafuchau Avatar asked Apr 14 '10 18:04

kafuchau


1 Answers

You can use the excellent xlwt module. It is very easy to use, and creates files in xls format (Excel 2003).

Here is an (untested!) example of use for a Django view:

from django.http import HttpResponse
import xlwt

def excel_view(request):
  normal_style = xlwt.easyxf("""
     font:
         name Verdana
     """) 
  response = HttpResponse(mimetype='application/ms-excel')
  wb = xlwt.Workbook()
  ws0 = wb.add_sheet('Worksheet')
  ws0.write(0, 0, "something", normal_style)
  wb.save(response)
  return response
like image 146
rob Avatar answered Oct 13 '22 03:10

rob