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.taojin.online.exercise.util; import com.taojin.online.exercise.entity.po.excel.ExcelData; import org.apache.poi.hssf.usermodel.HSSFDateUtil; 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.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCellStyle; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; public class ExcelUtil { //用于合并单元格所使用的的参数 public static Integer mergeStartRow = null; public static Integer mergeEndRow = null; public static Integer mergeStartColumn = null; public static Integer mergeEndColumn = null; public static void setMerCellParam(Integer mergeStartRow, Integer mergeEndRow, Integer mergeStartColumn, Integer mergeEndColumn){ mergeStartRow = mergeStartRow; mergeEndRow = mergeEndRow; mergeStartColumn = mergeStartColumn; mergeEndColumn = mergeEndColumn; } 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); //合并单元格,某行,到某行,某列,到某列 //sheet.addMergedRegion(new CellRangeAddress(1, 3, 0, 0)); 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); } } } /** * 合并单元格 * @author tongyao * @param sheet sheet页 * @param titleColumn 标题占用行 * @param cellIndex 那个单元格 */ public static void mergeCell(Sheet sheet, int titleColumn, int cellIndex){ //多少行 int rowCount = sheet.getPhysicalNumberOfRows(); String cellText = ""; //开始下标 int startIndex = 0; //结束下标 int endIndex = 0; Row row = null; Cell cell = null; for(int i = titleColumn;i<rowCount;i++){ row = sheet.getRow(i); cell = row.getCell(cellIndex); if(!cell.getStringCellValue().equals(cellText)){ if(startIndex != 0){ endIndex = (i-1); sheet.addMergedRegion(new CellRangeAddress(startIndex, endIndex, cellIndex, cellIndex)); } cellText = cell.getStringCellValue(); startIndex = i; } } endIndex = (rowCount-1); sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 0)); } /** * 根据HSSFCell类型设置数据 * index,cell 的index * @return */ public static String getCellString(Row row,int index) { Cell cell = row.getCell(index); String cellvalue = ""; if (cell != null) { switch (cell.getCellType()) { // 判断当前Cell的Type case Cell.CELL_TYPE_NUMERIC: case Cell.CELL_TYPE_FORMULA: // 判断当前的cell是否为Date if (HSSFDateUtil.isCellDateFormatted(cell)) { // 如果是Date类型则,转化为Data格式 //方法1:这样子的data格式是带时分秒的:2011-10-12 0:00:00 //cellvalue = cell.getDateCellValue().toLocaleString(); //方法2:这样子的data格式是不带带时分秒的:2011-10-12 Date date = cell.getDateCellValue(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); cellvalue = sdf.format(date); } case Cell.CELL_TYPE_STRING: // 如果当前Cell的Type为STRIN cellvalue = cell.getStringCellValue(); break; default: // 默认的Cell值 cellvalue = ""; } } if(cellvalue != null){ cellvalue = cellvalue.trim(); } return cellvalue; } }
# 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("用户信息数据"); //添加表头 List<String> titles = new ArrayList(); titles.add("title1"); titles.add("title2"); data.setTitles(titles); //添加列 List<List<Object>> rows = new ArrayList(); List<Object> row = null;
List<Modelxxx> listdata = new ArrayList<>();
for(int i=1; i<listdata.size();i++){ row=new ArrayList(); row.add(listdata[i].getName()); row.add(listdata[i].getName2()); rows.add(row); } data.setRows(rows); SimpleDateFormat fdate=new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); String fileName=fdate.format(new Date())+".xls"; ExcelUtils.exportExcel(response, fileName, 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)); index++; } return reply; } } ); return JsonResultBuilder.buildSuccess(null); } catch (Exception e) { return JsonResultBuilder.buildFailure("导入失败"); } }
转子:https://blog.csdn.net/Cool_breeze_Rainy/article/details/80572308
XSSFCellStyle titleStyle = wb.createCellStyle();