Spring Boot 导出Excel表格,以及导出批注
Spring Boot 导出Excel表格
添加支持
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
新建Excel实体类
import java.io.Serializable; import java.util.List; public class ExcelData implements Serializable { private static final long serialVersionUID = 4444017239100620999L; // 表头 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; } }
添加excel工具类
package com.tj.college.util; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Picture; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; 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.imageio.ImageIO; import javax.servlet.http.HttpServletResponse; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLEncoder; import java.util.List; public class ExcelUtils { public static void exportExcel(HttpServletResponse response, String fileName, ExcelData data, Boolean ... exportImg) throws Exception { // 告诉浏览器用什么软件可以打开此文件 response.setHeader("content-Type", "application/vnd.ms-excel"); // 下载文件的默认名称 response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "utf-8")); exportExcel(data, response.getOutputStream(), exportImg); } public static void exportExcel(ExcelData data, OutputStream out, Boolean ... img) throws Exception { XSSFWorkbook wb = new XSSFWorkbook(); try { String sheetName = data.getName(); if (null == sheetName) { sheetName = "Sheet1"; } XSSFSheet sheet = wb.createSheet(sheetName); writeExcel(wb, sheet, data, img); wb.write(out); } catch(Exception e){ e.printStackTrace(); }finally{ //此处需要关闭 wb 变量 out.close(); } } private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data,Boolean ...img) { int rowIndex = 0; rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles()); writeRowsToExcel(wb, sheet, data.getRows(), rowIndex, img); 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.setColor(IndexedColors.BLACK.index); XSSFCellStyle titleStyle = wb.createCellStyle(); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); titleStyle.setFont(titleFont); Row titleRow = sheet.createRow(rowIndex); // titleRow.setHeightInPoints(25); colIndex = 0; for (String field : titles) { 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, Boolean ...img) { int colIndex = 0; Font dataFont = wb.createFont(); dataFont.setFontName("simsun"); dataFont.setColor(IndexedColors.BLACK.index); XSSFCellStyle dataStyle = wb.createCellStyle(); dataStyle.setAlignment(HorizontalAlignment.CENTER); dataStyle.setVerticalAlignment(VerticalAlignment.CENTER); dataStyle.setFont(dataFont);for (List<Object> rowData : rows) { Row dataRow = sheet.createRow(rowIndex);
dataRow.setHeightInPoints(30);//设置cell行高 colIndex = 0; for (Object cellData : rowData) { Cell cell = dataRow.createCell(colIndex); if (cellData != null) { cell.setCellValue(cellData.toString()); } else { cell.setCellValue(""); } //导出图片 if(img != null && img.length>=1 && img[0] == Boolean.TRUE && cell.getStringCellValue().startsWith("http")){ String imgUrl = cellData.toString(); cell.setCellValue("");//上面是填了url文本的,会把cell撑开,所以设置为"",不影响img的宽高显示 try { URL url = new URL(imgUrl); // 读取网络图片并将其转换为BufferedImage对象 BufferedImage image = ImageIO.read(url); ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "png", os); InputStream is = new ByteArrayInputStream(os.toByteArray()); int pictureIdx = wb.addPicture(is, 4); // 创建绘图工具 CreationHelper helper = wb.getCreationHelper(); Drawing drawing = sheet.createDrawingPatriarch(); // 创建锚点 ClientAnchor anchor = helper.createClientAnchor(); anchor.setRow1(rowIndex); // 图片开始的行 anchor.setCol1(colIndex); // 图片开始的列 anchor.setRow2(rowIndex+1); // 图片结束的行 anchor.setCol2(colIndex+1); // 图片结束的列 // 创建图片 Picture picture = drawing.createPicture(anchor, pictureIdx); // 设置cell宽度为7个字符
sheet.setColumnWidth(colIndex, 7 * 256); }catch (Exception e){ e.printStackTrace(); } } 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); // } int maxWith = 256*255; //限制下最大宽度 if(newWidth > maxWith) { sheet.setColumnWidth(i, maxWith); }else 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); } }
ExcelUtils.java大概用得上(精简版,推荐)

package com.taojin.logistics.util; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.VerticalAlignment; 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.io.OutputStream; import java.net.URLEncoder; import java.util.List; 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")); exportExcel(data, response.getOutputStream()); } public static void exportExcel(ExcelData data, OutputStream out) throws Exception { XSSFWorkbook wb = new XSSFWorkbook(); try { String sheetName = data.getName(); if (null == sheetName) { sheetName = "Sheet1"; } 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.setColor(IndexedColors.BLACK.index); XSSFCellStyle titleStyle = wb.createCellStyle(); titleStyle.setAlignment(HorizontalAlignment.CENTER); titleStyle.setVerticalAlignment(VerticalAlignment.CENTER); titleStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); titleStyle.setFont(titleFont); Row titleRow = sheet.createRow(rowIndex); // titleRow.setHeightInPoints(25); colIndex = 0; for (String field : titles) { 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.setColor(IndexedColors.BLACK.index); XSSFCellStyle dataStyle = wb.createCellStyle(); dataStyle.setAlignment(HorizontalAlignment.CENTER); dataStyle.setVerticalAlignment(VerticalAlignment.CENTER); dataStyle.setFont(dataFont);for (List<Object> rowData : rows) { Row dataRow = sheet.createRow(rowIndex); 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); // } int maxWith = 256*255; //限制下最大宽度 if(newWidth > maxWith) { sheet.setColumnWidth(i, maxWith); }else 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); } }
# controller层,导出
import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import com.soft.ssmproject.entity.ExcelData; import com.soft.ssmproject.entity.ExcelInfo; import com.soft.ssmproject.tool.ExcelUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/excel") public class ExcelController { @RequestMapping(value = "/export", method = RequestMethod.POST) public void excel(HttpServletResponse response) throws Exception {
ExcelData data = new ExcelData();
data.setName("预警记录");
//添加表头
data.setTitles(Arrays.asList("客服","预警时间","预警类型","预警值","主管","店铺","说明"));
//添加列
List<List<Object>> rows = new ArrayList();
List<Object> row = null;
List<ModelBeanView> listdata = new ArrayList();
for (ModelBeanview : listdata) {
row = new ArrayList();
row.add(view.getName()+"("+ view.getTjkNumber() +")");
row.add(view.getWarningTime());
row.add(view.getWarningTypeName());
rows.add(row);
}
data.setRows(rows);
ExcelUtil.exportExcel(response, "预警记录.xlsx", data);
}
}
导入:
@RequestMapping(value = "/importExcel") public Object importReply(@RequestParam("file") MultipartFile file, String importType) { try { List<TrainReply> list = null; list = ExcelUtils.getExcelList(file.getInputStream(), new ExcelResolver<TrainReply>() { @Override public TrainReply resolve(org.apache.poi.ss.usermodel.Sheet sheet, Row row, int index) { TrainReply reply = null; if (index >= 1) { reply = new TrainReply(); reply.setQuicktext(ExcelUtil.getCellString(row, 0)); reply.setReplytext(ExcelUtil.getCellString(row, 1)); reply.setTypeName(ExcelUtil.getCellString(row, 2));
//注意导入相应的类,这里不再赘述,new XSSFClientAnchor()参数含义见地址:https://blog.csdn.net/zhayaobao1/article/details/135156562
//Drawing patr = sheet.createDrawingPatriarch();
//Comment comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, 4, 2, 6, 5));
//comment.setString(new XSSFRichTextString("加批注啊,尼玛啊"));
//cell.setCellComment(comment);
index++; } return reply; } } ); return JsonResultBuilder.buildSuccess(null); } catch (Exception e) { return JsonResultBuilder.buildFailure("导入失败"); } }
导入写法2,依赖更少:
public List<StaffUserInfo> importBlackNames(MultipartFile file)throws IOException { Workbook wb = WorkbookFactory.create(file.getInputStream()); Sheet sheet = wb.getSheetAt(0); int rows = sheet.getLastRowNum(); List<StaffUserInfo> list = new ArrayList<StaffUserInfo>(); int dataLine = 1; for (int i = 0; i <= rows; i++) { if(i < dataLine){ continue; } Row row = sheet.getRow(i); XXX staff = new XXX (); staff.setRealName(row.getCell(0).getStringCellValue()); list.add(staff); } wb.close(); return list; }
注:
导出批注写法
XSSFDrawing patr = sheet.createDrawingPatriarch(); XSSFComment comment = patr.createCellComment(new XSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); comment.setString(new XSSFRichTextString(msg)); cell.setCellComment(comment);
转子:https://blog.csdn.net/Cool_breeze_Rainy/article/details/80572308
XSSFCellStyle titleStyle = wb.createCellStyle();