开发者

How can we export data in JSP to excel sheet?

开发者 https://www.devze.com 2023-04-04 21:25 出处:网络
I am exporting data to an Excel sheet in JSP. <%@page import=\"java.io.*\"%> <%@page import=\"org.apache.poi.hssf.usermodel.HSSFSheet\"%>

I am exporting data to an Excel sheet in JSP.

<%@page import="java.io.*"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFSheet"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFWorkbook"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFRow"%>
<%@page import="org.apache.poi.hssf.usermodel.HSSFCell"%>
<% 
  String inj1=request.getParameter("inj"); 
  String ob=request.getParameter("ob"); 开发者_JS百科
  HSSFWorkbook wb = new HSSFWorkbook();
  HSSFSheet sheet = wb.createSheet("Excel Sheet"); 
  HSSFRow rowhead = sheet.createRow((short)0);
  rowhead.createCell((short)0).setCellValue("Injections");
  rowhead.createCell((short)1).setCellValue("OB");
  HSSFRow row = sheet.createRow((short)1);
  row.createCell((short)0).setCellValue(inj1);
  row.createCell((short)1).setCellValue(ob);
  FileOutputStream fileOut = new FileOutputStream("c:\\Injection_Details.xls");
  wb.write(fileOut);
  fileOut.close();
  out.println("Data is saved in excel file.");
%>

I am getting errors as

HSSFWorkbook cannot be resolved to a type

or

Only a type can be imported. org.apache.poi.hssf.usermodel.HSSFSheet resolves to a package.

How is this caused and how can I solve it?


HSSFWorkbook cannot be resolved to a type

That's just a compilation error. The mentioned class is missing in the classpath. In this particular case, you need to ensure that you've dropped the necessary JAR file(s) of Apache POI HSSF in your webapp's /WEB-INF/lib folder (which is part of the webapp's classpath).

This problem has nothing to do with JSPs. You would have exactly the same problem in a normal Java class where all that Java code actually belongs.


A simple Excel export without any additional libs:

  1. Write your ResultSet out as comma-delimited data in the JSP
  2. Set the ContentType on the response to Excel.

JSP Code; note the absence of line breaks in the JSP as those will mess up the CSV to Excel translation:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><% response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition","attachment;filename=export.csv"); %>
message_name,subject,sent_count,open_count,original_href,link_uuid,link_click_count
<c:forEach var="item" items="${myResultSet}">"<c:out value="${item.field1}" />","<c:out value="${item.field2}" />","<c:out value="${item.field3}" />"
0

精彩评论

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