springboot实现在浏览器上点击打印,自动读取数据库数据生成Excel文件

mac2025-10-21  5

1、效果图:

左图生成的excel,右图是数据库数据

2、jar包

生成Excel所有jar包

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml --> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.17</version> </dependency>

3、Excel封装类ExcelData.java

package com.lemon.pojo; import java.io.Serializable; import java.util.List; /** * Excel封装类 * @author lemon * @since 2019/11/1 0001 */ public class ExcelData implements Serializable { // 表头 private List<String> titles; // 数据 private List<List<Object>> rows; // 页签名称 private String name; public List<String> getTitles() { return titles; } public void setTitles(List<String> titles) { this.titles = titles; } public List<List<Object>> getRows() { return rows; } public void setRows(List<List<Object>> rows) { this.rows = rows; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

4、 Excel工具类ExcelUtils.java

package com.lemon.utils; import com.lemon.pojo.ExcelData; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder.BorderSide; import javax.servlet.http.HttpServletResponse; import java.awt.Color; import java.io.OutputStream; import java.net.URLEncoder; import java.util.List; /** * Excel工具类 * @author lemon * @since 2019/11/2 0002 */ public class ExcelUtils { public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data) throws Exception { // 告诉浏览器用什么软件可以打开此文件 response.setHeader("content-Type", "application/vnd.ms-excel"); // 下载文件的默认名称 response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8")); //把内容写入Excel表 exportExcel(data, response.getOutputStream()); } /** * 把内容写入Excel表 * @param data 传入要写的内容,此处以一个ExcelData分装类内容为例 * @param out 把输出流怼到要写入的Excel上,然后往里面写数据 * @author lemon * @since 2019/11/2 0002 */ public static void exportExcel(ExcelData data, OutputStream out) throws Exception { /**     使用的是JAVA POI实现的导出Excel表;     POI 提供了对2003版本的Excel的支持 ---- HSSFWorkbook     POI 提供了对2007版本以及更高版本的支持 ---- XSSFWorkbook */ //创建Excel工作簿 XSSFWorkbook wb = new XSSFWorkbook(); try { //设置工作表名称 为空默名认为Sheet1 String sheetName = data.getName(); if (null == sheetName) { sheetName = "Sheet1"; } //创建Excel工作表 XSSFSheet sheet = wb.createSheet(sheetName); //参数: 工作簿、工作表、数据 writeExcel(wb, sheet, data); wb.write(out); } catch(Exception e){ e.printStackTrace(); }finally{ //此处需要关闭 wb 变量 out.close(); } } private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) { int rowIndex = 0; //写标题内容 rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles()); //填充和颜色设置 writeRowsToExcel(wb, sheet, data.getRows(), rowIndex); //自动根据长度调整单元格长度 autoSizeColumns(sheet, data.getTitles().size() + 1); } //写标题内容 private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet, List<String> titles) { //行数 int rowIndex = 0; //列数 int colIndex = 0; //字体类 Font titleFont = wb.createFont(); titleFont.setFontName("simsun"); //titleFont.setBoldweight(Short.MAX_VALUE); // titleFont.setFontHeightInPoints((short) 14); titleFont.setColor(IndexedColors.BLACK.index); //创建单元格样式 XSSFCellStyle titleStyle = wb.createCellStyle(); //titleStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); //titleStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); //自定义颜色 titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192))); //titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND); //设置字体样式 titleStyle.setFont(titleFont); //设置边框 setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0))); //创建Excel工作表的行 Row titleRow = sheet.createRow(rowIndex); // titleRow.setHeightInPoints(25); colIndex = 0; for (String field : titles) { //创建Excel工作表指定行的单元格 Cell cell = titleRow.createCell(colIndex); //单元格内容 cell.setCellValue(field); //自定义颜色 cell.setCellStyle(titleStyle); colIndex++; } rowIndex++; return rowIndex; } //填充和颜色设置 private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex) { int colIndex = 0; Font dataFont = wb.createFont(); dataFont.setFontName("simsun"); // dataFont.setFontHeightInPoints((short) 14); dataFont.setColor(IndexedColors.BLACK.index); XSSFCellStyle dataStyle = wb.createCellStyle(); //dataStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); //dataStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER); dataStyle.setFont(dataFont); setBorder(dataStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0))); for (List<Object> rowData : rows) { Row dataRow = sheet.createRow(rowIndex); // dataRow.setHeightInPoints(25); colIndex = 0; for (Object cellData : rowData) { Cell cell = dataRow.createCell(colIndex); if (cellData != null) { cell.setCellValue(cellData.toString()); } else { cell.setCellValue(""); } cell.setCellStyle(dataStyle); colIndex++; } rowIndex++; } return rowIndex; } //自动根据长度调整单元格长度 private static void autoSizeColumns(Sheet sheet, int columnNumber) { for (int i = 0; i < columnNumber; i++) { int orgWidth = sheet.getColumnWidth(i); //自动根据长度调整单元格长度 sheet.autoSizeColumn(i, true); int newWidth = (int) (sheet.getColumnWidth(i) + 100); if (newWidth > orgWidth) { sheet.setColumnWidth(i, newWidth); } else { sheet.setColumnWidth(i, orgWidth); } } } //设置边框 private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) { //上边框 style.setBorderTop(border); //左边框 style.setBorderLeft(border); //右边框 style.setBorderRight(border); //下边框 style.setBorderBottom(border); //边框样式 style.setBorderColor(BorderSide.TOP, color); style.setBorderColor(BorderSide.LEFT, color); style.setBorderColor(BorderSide.RIGHT, color); style.setBorderColor(BorderSide.BOTTOM, color); } }

5、Excel服务类ExcelService.java

package com.lemon.service; import com.lemon.dao.ExcelDao; import com.lemon.pojo.ExcelData; import com.lemon.pojo.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class ExcelService { /** * 网评结果中的导出 * @author lemon * @since 2019/11/1 0001 */ public ExcelData getOutputExcelProjectData() { ExcelDao excelDao = new ExcelDao(); //Excel实体类 ExcelData excelData = new ExcelData(); //找到表中需要添加的数据 List<User> list = excelDao.getUserList(); //设置sheet名称 excelData.setName("用户信息"); //设置表头字段 List<String> titles = new ArrayList<String>(); titles.add("Id"); titles.add("账号"); titles.add("密码"); excelData.setTitles(titles); //把expertUserList转换为List<List<Object>> rows List<List<Object>> rows = new ArrayList<List<Object>>(); //加入数据 for (User user : list) { List<Object> row = new ArrayList<Object>(); row.add(user.getPassword()); row.add(user.getUsername()); row.add(user.getPassword()); rows.add(row); } //设置要输出的记录 excelData.setRows(rows); return excelData; } }

6、数据库操作 ExcelDao.java

可以整合mybatis、hibernate,进行数据库查询

public List<User> getUserList(){ String sql = "select * from user"; ........ }

7、ExcelController.java

package com.lemon.controller; import com.lemon.service.ExcelService; import com.lemon.utils.ExcelUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.servlet.http.HttpServletResponse; @Controller @RequestMapping("/excel") public class ExcelController { @Autowired private ExcelService excelService; /** * 去打印界面 * @author: lemon * @since: 2019/11/1 0001 */ @RequestMapping("/") public String toExcel(){ return "views/makeExcel"; } /** * 导出excel表 * @author lemon * @since 2019/11/1 0001 */ @RequestMapping("/makeExcel") public void makeExcel(HttpServletResponse response) throws Exception { //打印Excel表 ExcelUtils.exportExcel(response, "文件名.xlsx", excelService.getOutputExcelProjectData()); } }

8、makeExcel.html

打印界面:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>生成Excel表</title> <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script></head> <body> <button class="btn btn-primary" id="btn_export">生成Excel表</button> <script type="text/javascript"> //导出excel汇总表 $("#btn_export").click(function () { //打开新窗口 window.open("/excel/makeExcel"); }); </script> </body> </html>

9、浏览器输入:

http://localhost:8080/excel

 

 

最新回复(0)