<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>static/templates/*.xlsx</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.hutool.core.io.resource.Resource;
@RestController
@RequestMapping("excel")
public class ExcelDownloadController {
@RequestMapping(value="/downloadExcel")
public ResponseEntity<Resource> downloadExcel(HttpServletResponse response, HttpServletRequest request) {
try {
ClassPathResource cpr = new ClassPathResource("/static/templates/test.xlsx");
InputStream is = cpr.getInputStream();
Workbook workbook = new XSSFWorkbook(is);
String fileName = "test.xlsx";
downLoadExcel(fileName, response, workbook);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return new ResponseEntity<Resource>(HttpStatus.OK);
}
public static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) {
try {
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
workbook.write(response.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
}