Excel Tools
public class ExcelUtil { public static Final String EXTENSION_XLS = "xls" ; public static Final String EXTENSION_XLSX = "xlsx" ; / ** * <pre> * acquisition Workbook object (xls and xlsx different objects, but are Workbook implementation class) XLS: HSSFWorkbook * XLSX: XSSFWorkbook * * @param filePath * @return * @throws IOException </ pre> * / Private static the Workbook GetWorkbook (String filePath) throws IOException { the Workbook Workbook= null; // 检查 preReadCheck(filePath); InputStream is = new FileInputStream(filePath); // 获取workbook对象 if (filePath.endsWith(EXTENSION_XLS)) { workbook = new HSSFWorkbook(is); } else if (filePath.endsWith(EXTENSION_XLSX)) { workbook = new XSSFWorkbook(is); } is.close(); return workbook; } /** * 文件检查 * * @param filePath * @throws FileNotFoundException * @throws FileFormatException */ private static void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException { // 常规检查 File file = new File(filePath); if (!file.exists()) { throw new FileNotFoundException("传入的文件不存在:" + filePath); } if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) { throw new FileFormatException("传入的文件不是excel"); } } /** * 读取excel文件内容 * * @param filePath * @throws FileNotFoundException * @throws FileFormatException */ public static List<Map<String, String>> readAllExcel(String filePath) throws FileNotFoundException, FileFormatException { List<Map<String, String>> res = new ArrayList<>(); Workbook workbook = null; try { workbook = getWorkbook(filePath); // 读文件 一个sheet一个sheet地读取 for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) { Sheet sheet = workbook.getSheetAt(numSheet); if (sheet == null) { continue; } log.info("=======================" + sheet.getSheetName() + "========================="); int firstRowIndex = sheet.getFirstRowNum(); int lastRowIndex = sheet.getLastRowNum(); // 读取首行 即,表头 Row firstRow = sheet.getRow(firstRowIndex); if (firstRow != null) { for (int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) { Cell cell = firstRow.getCell(i); String cellValue = getCellValue(cell, true); } // 读取数据行 for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) { Map<String, String> map = new HashMap<>(); Row currentRow = sheet.getRow(rowIndex);// 当前行 int firstColumnIndex = currentRow.getFirstCellNum(); // 首列 int lastColumnIndex = currentRow.getLastCellNum();// 最后一列 String s = ""; for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) { Cell currentCell = currentRow.getCell(columnIndex);//Current cell String currentCellValue = getCellValue (CurrentCell, to true ); // current value of the cell map.put ( "Cell" + columnIndex, currentCellValue); S + = currentCellValue + "\ T" ; } log.info (S) ; res.add (Map); } log.info ( "read Excel ======== ========================= ===================== " ); } } } the catch (IOException E) { e.printStackTrace (); }the finally { IF (Workbook =! null ) { the try { workbook.close (); } the catch (IOException E) { e.printStackTrace (); } } } return RES; } / ** * takes a value of the cell * * @ param cell cell object * @param when treatAsStr is true, as the text to the values (to get the text, will not "1" take into "1.0") * @return * / Private static String getCellValue (the Cell Cell, Boolean treatAsStr) { IF (Cell == null ) { return "" ; } IF (treatAsStr) { // Although excel are provided in the text, but the text is further read the wrong numbers, such as " 1 "take into" 1.0 " // add the following sentence, the provisional it as text to read cell.setCellType (Cell.CELL_TYPE_STRING); } Switch (cell.getCellType ()) { Case Cell.CELL_TYPE_BOOLEAN: return String. valueOf (cell.getBooleanCellValue ()); Case Cell.CELL_TYPE_NUMERIC: return String.valueOf (cell.getNumericCellValue ()); default : return String.valueOf (cell.getStringCellValue ()); } } // ==================== ================================================== ========================== / ** * export to generate Excel spreadsheet * @param list a list objects * @param CLS mapping entity object class * @param sumData null * / // generate Excel, list derived data, list in the entity class, sumData aggregate data public static <Q> XSSFWorkbook createExcel (List <Q> List, class <Q> CLS, Q sumData) throws IOException, IllegalArgumentException, IllegalAccessException { XSSFWorkbook wb = new XSSFWorkbook(); Field[] fields = cls.getDeclaredFields(); ArrayList<String> headList = new ArrayList<String>(); // 添加合计数据 if (sumData != null) { list.add(sumData); } for (Field f : fields) { ExcelField field = f.getAnnotation(ExcelField.class); if (field != null) { headList.add(field.title()); } } XSSFCellStyle style = getCellStyle(wb); XSSFSheet sheet = wb.createSheet(); // 设置Excel表的第一行即表头 XSSFRow row = sheet.createRow(0); for (int i = 0; i < headList.size(); i++) { XSSFCell headCell = row.createCell(i); headCell.setCellType(Cell.CELL_TYPE_STRING); headCell.setCellStyle(style);// 设置表头样式 headCell.setCellValue(String.valueOf(headList.get(i))); // sheet.autoSizeColumn((short) i);// 设置单元格自适应 sheet.setColumnWidth(0, 15 * 256); } for (int i = 0; i < list.size(); i++) { XSSFRow rowdata = sheet.createRow(i + 1);// 创建数据行 Q q = list.get(i); Field[] ff = q.getClass().getDeclaredFields(); int j = 0; for (Field f : ff) { ExcelField field = f.getAnnotation(ExcelField.class); if (field == null) { continue; } f.setAccessible(true); Object obj = f.get(q); XSSFCell cell = rowdata.createCell(j); cell.setCellType(Cell.CELL_TYPE_STRING); // 当数字时 if (obj instanceof Integer) { cell.setCellValue((Integer)obj); // 将序号替换为123456 if (j == 0) cell.setCellValue(i + 1); } // When a string when the else IF (obj the instanceof String) cell.setCellValue ((String) obj); // if Boolean when the else IF (obj the instanceof Boolean) cell.setCellValue ((Boolean) obj); // if time when else iF (obj the instanceof a Date) cell.setCellValue ((a Date) obj); // when the time else iF (obj the instanceof Calendar) cell.setCellValue ((Calendar) obj); // if for fractional else if ( objinstanceof Double) cell.setCellValue((Double)obj); j++; } } if (sumData != null) { int rowIndex = list.size(); XSSFRow sumRow = sheet.getRow(rowIndex); XSSFCell sumCell = sumRow.getCell(0); sumCell.setCellStyle(style); sumCell.setCellValue("合计"); } return wb; } // 导出 public static void writeExcel(HttpServletResponse response, String fileName, XSSFWorkbook wb) throws IOException { response.setContentType("application/vnd.ms-excel"); response.setHeader("Content-disposition", "attachment; filename=" + fileName); OutputStream ouputStream = null; try { ouputStream = response.getOutputStream(); wb.write(ouputStream); } finally { ouputStream.close(); } } // 表头样式 public staticGetCellStyle XSSFCellStyle (XSSFWorkbook WB) { XSSFCellStyle style = wb.createCellStyle (); the Font font = wb.createFont (); font.setFontName ( "Song" ); font.setFontHeightInPoints (( Short ) 12 is); // set the font size font .setBoldweight (HSSFFont.BOLDWEIGHT_BOLD); // bold style.setFillForegroundColor (HSSFColor.LIME.index); // set the background color style.setFillPattern (HSSFCellStyle.SOLID_FOREGROUND); style.setAlignment (HSSFCellStyle.SOLID_FOREGROUND); // make unit grid centered style.setAlignment (HSSFCellStyle.ALIGN_CENTER); // left center style.setVerticalAlignment (HSSFCellStyle.VERTICAL_CENTER); // vertically centered style.setWrapText ( to true ); // Set wrap style.setFont (font); return style; } public static void main (String [] args) throws FileFormatException, a FileNotFoundException { } }
Excel export class notes
@Target ({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE}) @Retention (RetentionPolicy.RUNTIME) public @ interface ExcelField { // derived excel in the field name String title (); }
Import Contorller
/** * 导入 * @return Result */ @PostMapping("/import/{id}") public Result importRecommender(@RequestParam MultipartFile file, @PathVariable String id) { try { String ext = FilenameUtils.getExtension(file.getOriginalFilename()); String reName = RandomStringUtils.randomAlphanumeric(32).toLowerCase() + "."+ ext; String imgPath = ImgPathEnum.getPath(8, id); String realPath = PathUtil.getPorjectPath() + Constant.BASC_PATH + imgPath; FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, reName)); List<Map<String, String>> list = ExcelUtil.readAllExcel(realPath + reName); Recommender recommender = new Recommender(); recommender.setPlatformId(id); for (Map<String, String> map : list) { recommender.setCreateDate(new Date()); recommender.setName(map.get("cell0"));//cell0 -> 推荐人姓名 recommender.setPhone(map.get("cell1"));//cell1 -> 推荐人电话 recommender.setIdcard (map.get ( "Cell2")); // Cell2 -> Recommended id String dotCode = map.get ( "cell3"); // channel network coding Dot dot = dotService.findByCodeAndPlatformId (map.get ( "the cell 3" ), ID); IF (DOT == null ) the throw new new Exception ( "channel coding [" + dotCode + "] system does not exist!" ); recommender.setDotId (ObjectUtils.toString (dot.getDotId ( ))); // the cell 3 -> dot coding SYSUSER User = sysUserService.findUserByPlatformIdAndDevelopmentPeo (ID, as map.get ( "CELL4" )); if(the User == null ) the throw new new Exception ( "development of the human coding [" + map.get ( "cell4" ) + "] system does not exist!" ); recommender.setUserId (user.getUserId ()); // Cell 5 -> user (human development) ID recommenderService.insert (Recommender); } } the catch (Exception E) { return Result.error ( "bulk import failed:" + e.getMessage ()); } return result.OK (); }
Export Contorller
/** * 导出 * @param response 响应 * @return Result */ @PostMapping("/export/{id}") public void export(HttpServletResponse response, @PathVariable String id) { try { List<Recommender> recommenderList = recommenderService.findExcelListByPlatformId(id); XSSFWorkbook wb = ExcelUtil.createExcel(recommenderList, Recommender.class, null); String filename = getExcelName("Recommender.xlsx"); response.setHeader("Content-Disposition", "attachment; filename=\"" + KeyUtil.random(16)); ExcelUtil.writeExcel(response, filename, wb); } catch (Exception e) { sendResponseErrorMsg(response, e); } } // 转化为excel名称 private String getExcelName(String filename) throws UnsupportedEncodingException { String excelName = StringUtils.join(Collections.singleton(filename), ".xlsx"); return URLEncoder.encode(excelName, "UTF-8"); }