内容来源于网络,侵删。
1、需要的jar包
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.14</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.14</version> </dependency>
2、工具包,可根据实际业务调整工具包
package com.jbf.util; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.net.URLEncoder; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; /********************************* * 类描述: * @author huangsz * @date 2019/11/21 * @version v1.0 **********************************/ public class ExcelUtil { public static void main(String[] args) throws Exception{ } public static void exportExcel(HttpServletResponse response, String title, String subheading, List<String> header, List<List<String>> dataList) throws Exception { // 创建工作簿 HSSFWorkbook workbook = new HSSFWorkbook(); // 创建行 HSSFCellStyle cellStyle = workbook.createCellStyle(); // 居中 cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个sheet HSSFSheet sheet = workbook.createSheet("sheet名字"); // 创建一个标题 CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, header.size()); // 创建一个副标题 CellRangeAddress cellRangeAddress2 = new CellRangeAddress(1, 1, 0, header.size()); sheet.addMergedRegion(cellRangeAddress); sheet.addMergedRegion(cellRangeAddress2); // 标题,居中 HSSFRow row0 = sheet.createRow(0); HSSFCell cell0 = row0.createCell(0); cell0.setCellValue(title); cell0.setCellStyle(cellStyle); // 第一行 HSSFRow row1 = sheet.createRow(1); HSSFCell cell1 = row1.createCell(0); // 副标题 cell1.setCellValue(subheading); cell1.setCellStyle(cellStyle); // 表头 HSSFRow row = sheet.createRow(2); HSSFCell cell = null; for (int i = 0; i < header.size(); i++) { cell = row.createCell(i); cell.setCellValue(header.get(i)); cell.setCellStyle(cellStyle); } // 数据 for (int i = 0; i < dataList.size(); i++) { row = sheet.createRow(i + 3); for (int j = 0; j < dataList.get(i).size(); j++) { row.createCell(j).setCellValue(dataList.get(i).get(j)); } } OutputStream out = response.getOutputStream(); // 设置页面不缓存 response.reset(); String fileName = URLEncoder.encode(title, "UTF-8"); response.setCharacterEncoding("UTF-8"); response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xls"); response.setContentType("application/msexcel"); workbook.write(out); out.close(); } /** * 导入数据 * @param file 表 * @param sheetIndex sheet索引值 * @param headerIndex 表头的索引(用于获取共多少列以及第几行开始读数据) * @return * @throws Exception */ public static List<List<Object>> importExcel(MultipartFile file, int sheetIndex, int headerIndex) throws Exception { List<List<Object>> data = new ArrayList<>(); Workbook workbook = getWorkbook(file); // 导入某页sheet if (sheetIndex >-1) { Sheet sheet = workbook.getSheetAt(sheetIndex); List<List<Object>> lists = importSheet(sheet, headerIndex); data.addAll(lists); } else { // 导入全部 //导入全部 for (int i = 0; i < workbook.getNumberOfSheets(); i++) { Sheet sheet = workbook.getSheetAt(i); if (sheet == null) { continue; } List<List<Object>> lists = importSheet(sheet, headerIndex); data.addAll(lists); } } return data; } private static List<List<Object>> importSheet(Sheet sheet, int headerIndex) throws Exception { List<List<Object>> data = new ArrayList<>(); // 获取行数 int row = sheet.getLastRowNum(); //row = -1 表格中没有数据 //row = headerIndex 表格中表头以下没有数据(指没有有用数据) if (row == -1 || row == headerIndex) { throw new Exception("表格中没有有用数据!"); } // 获取列数 int columnNum = sheet.getRow(headerIndex).getPhysicalNumberOfCells(); // 从表头下一行开始取数据 for (int i = headerIndex + 1; i <= row; i++) { Row row1 = sheet.getRow(i); List<Object> list = new ArrayList<>(); if (row1 != null) { for (int j = 0; j < columnNum; j++) { list.add(getCellValue(row1.getCell(j))); } } data.add(list); } return data; } private static Object getCellValue(Cell cell) { String cellValue = ""; DecimalFormat df = new DecimalFormat("#"); switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: cellValue = cell.getRichStringCellValue().getString().trim(); break; case HSSFCell.CELL_TYPE_NUMERIC: cellValue = df.format(cell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BOOLEAN: cellValue = String.valueOf(cell.getBooleanCellValue()).trim(); break; case HSSFCell.CELL_TYPE_FORMULA: cellValue = cell.getCellFormula(); break; default: cellValue = ""; } return cellValue.trim(); } private static Workbook getWorkbook(MultipartFile file) throws Exception{ Workbook workbook = null; String xls = "xls"; String xlsx = "xlsx"; // 获取文件名 String fileName = file.getOriginalFilename(); if (fileName.endsWith(xls)) { workbook = new HSSFWorkbook(file.getInputStream()); } else if(fileName.endsWith(xlsx)){ workbook = new XSSFWorkbook(file.getInputStream()); } else { throw new Exception("文件格式有误!"); } return workbook; } }
3、验证
@GetMapping("/exe") public void excel(HttpServletResponse response) { List<String> header = new ArrayList<>(); header.add("评论Id"); header.add("被评论人Id"); header.add("内容"); TestBean bean = new TestBean(); List<List<String>> dataList = new ArrayList<>(); for (int i = 1; i <= 5; i++) { List<String> data = new ArrayList<>(); data.add(i+""); data.add(i+1+""); data.add("第" + i + "条评论"); dataList.add(data); } try { ExcelUtil.exportExcel(response,"标题","副标题",header,dataList); } catch (Exception e) { e.printStackTrace(); } } @PostMapping("/up") public void upload(@RequestParam("file") MultipartFile file){ try { List<List<Object>> lists = ExcelUtil.importExcel(file, 0,2); System.out.println(lists.size()); for (List<Object> list : lists) { for (Object o : list) { System.out.println(o); } } } catch (Exception e) { e.printStackTrace(); } }