views:

473

answers:

3

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.

+2  A: 

Use CSV. There's a module in Python ("csv") to generate it, and excel can read it natively.

moshez
From a user interface standpoint, how would I present the CSV file to the user? The user would already be looking at the page, so would they click a link that then goes back to some view function and generates the CSV file, and then...?
kchau
Also, a CSV wouldn't keep any formatting that my HTML table already has, right?
kchau
Right. With CSV the results are not that good looking; it is not only a matter of styles, but even the column width is just the standard one. As there are ways to produce native Excel files, I would not recommend using CSV.
Roberto Liffredo
But the principle is the important: you're not converting the HTML table to Excel, you're getting the view function to output the same data in a different format.
Daniel Roseman
+4  A: 

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
Roberto Liffredo
A: 

Excel support opening an HTML file containing a table as a spreadsheet (even with CSS formatting).

You basically have to serve that HTML content from a django view, with the content-type application/ms-excel as Roberto said.

Or if you feel adventurous, you could use something like Downloadify to prepare the file to be downloaded on the client side.

Clément