Yoda_SO_99999
Yoda_SO_99999

Reputation: 31

MIME type/Content-type for opening CSV files using Excel in IE & Firefox

I have been having an issue with getting CSV output to be recognized & opened in Excel. In my web application I have a java servlet that returns search results to the user. The search results are delivered by an Apache Solr server. There is an option on the GUI front-end that allows the user to request the search results in “CSV” format. If this option is selected then the query is re-run against Solr by adding a "wt=csv" param. Then a java filter adds headers to return the results as CSV formatted-text. But it’s not working correctly.

I have tried a variety of headers & combinations –

  //((HttpServletResponse)response).setHeader("Content-Type", "application/octet; charset=utf-8");
  ((HttpServletResponse)response).setHeader("Content-Type", "text/csv");
  //((HttpServletResponse)response).setHeader("Content-Type", "application/vnd.ms-excel");
  //((HttpServletResponse)response).setHeader("Cache-Control", "private, private,max-age=0,must-revalidate");
  //((HttpServletResponse)response).setHeader("Content-Encoding", "gzip");
  //((HttpServletResponse)response).setHeader("Content-Encoding", "binary");
  ((HttpServletResponse)response).setHeader("Content-Disposition", "attachment; filename=Download.CSV");
  //((HttpServletResponse)response).setHeader("Content-Disposition", "inline; filename=Download.CSV;");

But none of them seem to be working. I used Firefox to inspect the headers that are being sent back & I see the following –

Content-Disposition:attachment; filename=Download.CSV

Content-Type:text/plain;charset=UTF-8

Server:Jetty(7.x.y-SNAPSHOT)

Transfer-Encoding:chunked

Vary:Accept-Encoding

Even though the content-type is specified as csv Or excel; when it reaches the browser it’s being interpreted as text/plain & I think that’s the issue. Not sure what header Or encoding I should be setting? Any suggestions? Thanks.

Upvotes: 3

Views: 27075

Answers (1)

Laura A. R.
Laura A. R.

Reputation: 11

I'm doing something similar and this is part of the code I'm using:

    Date dt = new Date();
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HHmmss");
    String filename = fmt.format(dt) + ".csv";
    //Setup the output
    String contentType = "application/vnd.ms-excel";
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse)fc.getExternalContext().getResponse();
    response.setHeader("Content-disposition","attachment; filename=" + filename);
    response.setContentType(contentType);

Note that I use the variable "contentType" to tell the servlet what kind of file will be generated.

Hope it works for you.

Upvotes: 1

Related Questions