开发者

Excel spreadsheet created with JSP does not show unicode characters in Excel

I have an app that I need to display Unicode information to an excel spreadsheet that is converted from a table in JSP. The unicode info displays correctly in JSP, but in Excel, it does not show international characters.

Basically to show the jsp table in Excel and start with the 开发者_如何转开发following line:

response.setHeader("Content-Disposition","attachment;filename=report.xls");

Then below there are <td>'s and <tr>'s that display the information in a tabular format.

I'm thinking I need another line under the response.setHeader line in order for unicode to render correctly.

Any thoughts?


You shouldn't fool Excel with a HTML <table> with the wrong content type and file extension. Rather use a servlet to create a real and fullworthy binary XLS file with help of for example Apache POI HSSF or JExcelAPI. They'll take care about the proper character encoding.

You can find a basic kickoff example in the JExcelAPI FAQ, check the section How do I output an Excel file from a Servlet? Here's an extract of relevance (disclaimer: this is a 100% copypaste, it's not my code style and the class should actually be placed inside a package):

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class Sample extends HttpServlet
{
 public void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException
 {
  OutputStream out = null;
  try
  {
   response.setContentType("application/vnd.ms-excel");
   response.setHeader("Content-Disposition", "attachment; filename=sampleName.xls");
   WritableWorkbook w = Workbook.createWorkbook(response.getOutputStream());
   WritableSheet s = w.createSheet("Demo", 0);
   s.addCell(new Label(0, 0, "Hello World"));
   w.write();
   w.close();
  } catch (Exception e)
  {
   throw new ServletException("Exception in Excel Sample Servlet", e);
  } finally
  {
   if (out != null)
    out.close();
  }
 }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜