I had the opportunity to create a Servlet that can download Excel, and I was quite addicted to it, so I would like to keep a sample of it. Apache POI is used to operate Excel from Java, but the installation method and usage method are omitted.
First, create the Servlet class as follows.
package servlet;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*Servlet to download Excel.
* @author nekoTheShadow
*
*/
@WebServlet("/download")
public class ExcelDownloadServlet extends HttpServlet {
/**
*Display the download page.
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/download.jsp").forward(request, response);
}
/**
*Excel is generated based on the POSTed form data and downloaded.
* @throws UnsupportedEncodingException
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//UTF the character code of the request-Convert to 8.
request.setCharacterEncoding("UTF-8");
//Get a request query.
String param1 = (String) request.getParameter("param1");
String param2 = (String) request.getParameter("param2");
String param3 = (String) request.getParameter("param3");
//Generate file name:The file name is the download date.
SimpleDateFormat simpleDataFormat = new SimpleDateFormat("yyyy-MM-dd");
String filename = simpleDataFormat.format(new Date()) + ".xlsx";
//Set the response header.
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("content-disposition", String.format("attachment; filename=\"%s\"", filename));
response.setCharacterEncoding("UTF-8");
//Workbooks and byte streams(response)To generate.
//These two must be closed=> try-with-Utilize the resource statement,
try (Workbook workbook = new XSSFWorkbook();
OutputStream outputStream = response.getOutputStream()) {
//Generate a sheet:Actually, complicated logic is used, but this time it is a sample, so I will keep it simple.
Sheet sheet = workbook.createSheet();
sheet.createRow(1).createCell(1).setCellValue(param1);
sheet.createRow(2).createCell(1).setCellValue(param2);
sheet.createRow(3).createCell(1).setCellValue(param3);
//Output the workbook to the response.
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
The next time you access download
, the download.jsp
will be displayed as follows. Place it directly under the / WEB-INF / jsp
directory.
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Excel Download</h1>
<form method="post" action="/excel/download">
<p><label>Parameter 1:</label><input type="text" name="param1" /></p>
<p><label>Parameter 2:</label><input type="text" name="param2" /></p>
<p><label>Parameter 3:</label><input type="text" name="param3" /></p>
<p><input type="submit" value="Download Excel" /></p>
</form>
</body>
</html>
After preparing the necessary files, deploy and access / download
and you should see a page like this:
After that, enter the parameters and press Download Excel
to download the Excel file whose title is the date.
And when you actually open the downloaded Excel file, you can see that the Excel file is created properly without any damage.
Is the response header setting particularly important this time? Honestly, I don't see ʻapplication / vnd.openxmlformats-officedocument.spreadsheetml.sheet specified in content-type, and the attribute itself,
content-disposition`, is unfamiliar to me and I got stuck in it. It was a point.
//Set the response header.
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("content-disposition", String.format("attachment; filename=\"%s\"", filename));
response.setCharacterEncoding("UTF-8");