(1),后台java代码响应xls表格文件到客户端
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
/**
* @date: 2022/11/5 23:14
* @desc: 测试控制类
*/
@Controller
@RequestMapping(value = "/studentConter")
public class StudentController {
@RequestMapping(value = "/exportExcelFile")
public void exportExcelFile(HttpServletRequest request
, HttpServletResponse response ) {
response.setContentType("application/vnd.ms-excel");
String fileName = "";
OutputStream outputStream;
try {
fileName = URLEncoder.encode("导出文件名称1", "UTF-8");
response.setHeader("content-disposition", "attachment;filename="+ fileName + ".xls");
XSSFWorkbook xssfWorkbook = writeTextWorkbook();
outputStream = response.getOutputStream();
xssfWorkbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception ex1) {
ex1.printStackTrace();
}
}
// 把内容写入表格文件中
private XSSFWorkbook writeTextWorkbook() {
XSSFWorkbook xssfWorkbook = new XSSFWorkbook();
XSSFSheet xssfSheet = xssfWorkbook.createSheet();
// 在工作薄第一行填充数据
XSSFRow xssfRow = xssfSheet.createRow(0);
XSSFCell xssfCellIdx0 = xssfRow.createCell(0);
xssfCellIdx0.setCellValue("第一行第一个单元格内容");
XSSFCell xssfCellIdx1 = xssfRow.createCell(1);
xssfCellIdx1.setCellValue("第一行第二个单元格内容");
return xssfWorkbook;
}
}
(2),jar包依赖参考上一篇:06,SpringMVC项目导入wps表格文件
(3),测试请求地址
http://localhost:8085/bl_mave_wf_war_exploded/studentConter/exportExcelFile