: SpringEL는 참조 할 수 있습니다 https://www.cnblogs.com/yangzhilong/p/11282560.html
POI 3.1.7, 봄 쓰기 5.1.7 기준으로합니다.
엑셀 이후 # 키워드의 수이고, 모든 나는 # 문자를 대체하는 $를 {} 사용합니다.
핵심 범주 도움말 :
패키지 com.longge.util; 수입 java.io.InputStream를; 수입 인 java.util.ArrayList; 수입 은 java.util.List; 수입 org.apache.poi.ss.usermodel.Cell; 수입 org.apache.poi.ss.usermodel.CellStyle; 수입 org.apache.poi.ss.usermodel.CellType; 수입 org.apache.poi.ss.usermodel.Row; 수입 org.apache.poi.ss.usermodel.Sheet; 수입 org.apache.poi.ss.usermodel.Workbook; 수입 org.apache.poi.ss.usermodel.WorkbookFactory; 수입 org.springframework.core.io.ClassPathResource; 수입org.springframework.expression.EvaluationContext; 수입 org.springframework.expression.ExpressionParser; 수입 org.springframework.expression.spel.standard.SpelExpressionParser; 수입 org.springframework.expression.spel.support.StandardEvaluationContext; 수입 org.springframework.util.CollectionUtils; / ** * @author yangzhilong * @date 2019년 8월 1일 * / 공용 클래스 ExcelTemplateWriteUtils { / ** * 템플릿 통합 문서를 엑셀 얻을 * @param templateFilePath 예 : 정적 / excelTemplate / xx.xlsx * @return * / 공공 정적 통합 문서 getWorkbook (문자열 templateFilePath) { 시도 { 의 InputStream이다; 경우 (templateFilePath.startsWith ( "/" )) { 이다 = ExcelTemplateWriteUtils. 클래스 .getResourceAsStream (templateFilePath); } 다른 { 이다 = 새로운 ClassPathResource가 (templateFilePath) .getInputStream (); } 리턴 WorkbookFactory.create는 (IS); } 캐치 (예외 전자) { 던져 새로운 RuntimeException을 (전자); } } / ** * @param의 시트 * @param의 templateRowIndex * @param의 목록 * / 공공 정적 무효 fillDataWithTemplate (시트 시트 int로 templateRowIndex,리스트 <? 연장 개체> 목록) { INT tIndex = templateRowIndex; 행 templateRow = sheet.getRow (templateRowIndex); 경우 (CollectionUtils.isEmpty (목록)) { sheet.removeRow (templateRow); } 다른 { 목록<object> 템플릿 = 새로운 ArrayList를 <> (templateRow.getPhysicalNumberOfCells ()); 목록 <CellStyle> sytles = 새로운 ArrayList를 <> (templateRow.getPhysicalNumberOfCells ()); templateRow.forEach (셀 -> { sytles.add (cell.getCellStyle ()); cell.getCellStyle (); CellType 타입 = cell.getCellTypeEnum () 경우 (CellType.NUMERIC.equals (식)) { template.add ( cell.getNumericCellValue ()); } 다른 경우 (CellType.STRING.equals (유형)) { 문자열 값 =cell.getStringCellValue (); 경우 (value.startsWith ( "$ {" )) { 값 = formatEl (값); } template.add (값); } 다른 경우 (CellType.BLANK.equals (유형)) { template.add ( 널 ); } 다른 { 던져 새로운 ( "세포 유형을 지원할 수 없습니다 :"+의 RuntimeException을 type.toString ()); } }); ExpressionParser 파서 = 새로운SpelExpressionParser (); 대 ( int로 ; 나는 LEN <I는 I = + + 0 = LEN는 list.size () {) 개체 항목 = list.get (I); 행 newRow = sheet.createRow (tIndex ++ ); EvaluationContext 컨텍스트 = 새로운 StandardEvaluationContext의 (); context.setVariable ( "항목" , 항목); ForEachUtils.forEach ( 0, 템플릿 (지표 값) -> { 셀 newCell = ! = newRow.createCell (인덱스); newCell.setCellStyle (sytles.get (지수)); 경우 ( 널 값) { 경우 (값 instanceof는 문자열) { 문자열 V = (문자열) 값; 경우 (v.startsWith ( "#" )) { V = parser.parseExpression (V) .getValue (문맥, 문자열. 클래스 ); } newCell.setCellValue (V); } 다른 경우 (값 instanceof를 수) { newCell.setCellValue (((수)의 값) .doubleValue ()); } } }); } } } 개인 정적 문자열 formatEl (문자열 엘) { 반환 el.replace ( "$ {", "#") 교체 ( "}", "." ); } }
단위 테스트 클래스 :
패키지 com.longge.util; 가져 정적 org.junit.Assert.assertEquals을; 수입 java.io.File에; 수입 java.io.FileOutputStream의; 수입 인 java.util.ArrayList; 수입 java.util.HashMap에; 수입 은 java.util.List; 수입 java.util.Map; 수입 java.util.UUID; 수입 org.apache.poi.ss.usermodel.Sheet; 수입 org.apache.poi.ss.usermodel.Workbook; 수입 org.junit.Test; 수입 com.nike.cig.dto.CustomerDto; / ** * @author의 yangzhilong * @date 2019년 8월 1일 * / 공용 클래스 ExcelTemplateWriteUtilsTest는 { @Test 공개 공극 시험 () 가 발생 예외 { 문자열 경로 = "UTIL / template.xlsx" ; // 문자열 경로 = "/util/template.xlsx"; 통합 된 통합 = ExcelTemplateWriteUtils.getWorkbook (경로); 시트 시트 = workbook.getSheetAt (0 ); 목록 <CustomerDto> 목록 = 새로운 ArrayList를 <> (10 ); 위한 ( int로 ; I <10, I = 0 난 ++ ) { CustomerDto의 DTO = 새로운CustomerDto (); dto.setChineseName ( "이름"+ I); dto.setCustomerCode ( "코드 :"+ I); dto.setOwnerGroup ( "그룹"+ I); 에는 list.add (DTO); } ExcelTemplateWriteUtils.fillDataWithTemplate (시트, 1 ,리스트); assertEquals (sheet.getPhysicalNumberOfRows (), 11 ); workbook.write ( 새 FileOutputStream에 ( 새로운 파일 ( "C : \\ 사용자 \\ RYan27 \\ 바탕 화면 \\ 시험 \\"+ UUID.randomUUID의 toString () () + ".XLSX." ))); workbook.close (); } }
템플릿 파일 :
최종 문서가 생성되는 실시 예 :