Java POI导出Excel表格(二)

    xiaoxiao2025-02-19  49

    先浏览下前篇文章 https://blog.csdn.net/weixin_39816139/article/details/90576364 运行环境:ssm + mysql

    控制层 @Controller public class ReportFormController { @Autowired private ExeclMapper execlMapper; @RequestMapping("/excel/export") public void export(HttpServletResponse response) throws IOException { response.setCharacterEncoding("UTF-8"); List<Execl> list = execlMapper.findObject(); // System.out.println(list); //创建excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //创建sheet页 HSSFSheet sheet = wb.createSheet("员工信息表"); //创建标题行 HSSFRow titleRow = sheet.createRow(0); titleRow.createCell(0).setCellValue("id"); titleRow.createCell(1).setCellValue("姓名"); titleRow.createCell(2).setCellValue("年龄"); titleRow.createCell(3).setCellValue("性别"); //遍历将数据放到excel列中 for (Execl user : list) { HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum() + 1); dataRow.createCell(0).setCellValue(user.getId()); dataRow.createCell(1).setCellValue(user.getName()); dataRow.createCell(2).setCellValue(user.getAge()); dataRow.createCell(3).setCellValue(user.getSex()); } response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String("在职员工名单".getBytes(), "iso-8859-1") + ".xls"); OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } } 持久层 public interface ExeclMapper { List<Execl> findObject(); } pojo对象 @Data public class Execl { public Integer id; public String name; public Integer age; public String sex; } mapper文件 <select id="findObject" resultType="com.ssm.cn.pojo.Execl"> select id, name, age, sex from user </select> 数据库

    运行地址栏 http://localhost:8080/{你的项目名称}/excel/export

    最新回复(0)