├── .mvn └── wrapper │ ├── maven-wrapper.jar │ └── maven-wrapper.properties ├── src ├── main │ ├── resources │ │ └── application.properties │ └── java │ │ └── com │ │ └── howie │ │ └── easyexcelmethodencapsulation │ │ ├── excel │ │ ├── ExcelException.java │ │ ├── ExcelListener.java │ │ ├── ExcelWriterFactroy.java │ │ └── ExcelUtil.java │ │ ├── EasyexcelMethodEncapsulationApplication.java │ │ └── test │ │ ├── ExportInfo.java │ │ ├── ImportInfo.java │ │ └── ExcelController.java └── test │ └── java │ └── com │ └── howie │ └── easyexcelmethodencapsulation │ └── EasyexcelMethodEncapsulationApplicationTests.java ├── .gitignore ├── pom.xml ├── mvnw.cmd ├── README.md └── mvnw /.mvn/wrapper/maven-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HowieYuan/easyexcel-encapsulation/HEAD/.mvn/wrapper/maven-wrapper.jar -------------------------------------------------------------------------------- /.mvn/wrapper/maven-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.5.3/apache-maven-3.5.3-bin.zip 2 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.http.multipart.max-file-size=100MB 2 | spring.http.multipart.max-request-size=100MB 3 | spring.http.multipart.maxFileSize=100MB 4 | spring.http.multipart.maxRequestSize=1000MB 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target/ 2 | !.mvn/wrapper/maven-wrapper.jar 3 | 4 | ### STS ### 5 | .apt_generated 6 | .classpath 7 | .factorypath 8 | .project 9 | .settings 10 | .springBeans 11 | .sts4-cache 12 | 13 | ### IntelliJ IDEA ### 14 | .idea 15 | *.iws 16 | *.iml 17 | *.ipr 18 | 19 | ### NetBeans ### 20 | /nbproject/private/ 21 | /build/ 22 | /nbbuild/ 23 | /dist/ 24 | /nbdist/ 25 | /.nb-gradle/ -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/excel/ExcelException.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.excel; 2 | 3 | /** 4 | * Created with IntelliJ IDEA 5 | * 6 | * @Author yuanhaoyue swithaoy@gmail.com 7 | * @Description Excel 解析 Exception 8 | * @Date 2018-06-06 9 | * @Time 15:56 10 | */ 11 | public class ExcelException extends RuntimeException { 12 | public ExcelException(String message) { 13 | super(message); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/EasyexcelMethodEncapsulationApplication.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class EasyexcelMethodEncapsulationApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(EasyexcelMethodEncapsulationApplication.class, args); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/test/java/com/howie/easyexcelmethodencapsulation/EasyexcelMethodEncapsulationApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class EasyexcelMethodEncapsulationApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/test/ExportInfo.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.test; 2 | 3 | import com.alibaba.excel.annotation.ExcelProperty; 4 | import com.alibaba.excel.metadata.BaseRowModel; 5 | 6 | /** 7 | * Created with IntelliJ IDEA 8 | * 9 | * @Author yuanhaoyue swithaoy@gmail.com 10 | * @Description 导出 Excel 时使用的映射实体类,Excel 模型 11 | * @Date 2018-06-06 12 | * @Time 17:03 13 | */ 14 | public class ExportInfo extends BaseRowModel { 15 | @ExcelProperty(value = "姓名" ,index = 0) 16 | private String name; 17 | 18 | @ExcelProperty(value = "年龄",index = 1) 19 | private String age; 20 | 21 | @ExcelProperty(value = "邮箱",index = 2) 22 | private String email; 23 | 24 | @ExcelProperty(value = "地址",index = 3) 25 | private String address; 26 | 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getAge() { 36 | return age; 37 | } 38 | 39 | public void setAge(String age) { 40 | this.age = age; 41 | } 42 | 43 | public String getEmail() { 44 | return email; 45 | } 46 | 47 | public void setEmail(String email) { 48 | this.email = email; 49 | } 50 | 51 | public String getAddress() { 52 | return address; 53 | } 54 | 55 | public void setAddress(String address) { 56 | this.address = address; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/test/ImportInfo.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.test; 2 | 3 | import com.alibaba.excel.annotation.ExcelProperty; 4 | import com.alibaba.excel.metadata.BaseRowModel; 5 | 6 | /** 7 | * Created with IntelliJ IDEA 8 | * 9 | * @Author yuanhaoyue swithaoy@gmail.com 10 | * @Description 导入 Excel 时使用的映射实体类,Excel 模型 11 | * @Date 2018-06-05 12 | * @Time 21:41 13 | */ 14 | public class ImportInfo extends BaseRowModel { 15 | @ExcelProperty(index = 0) 16 | private String name; 17 | 18 | @ExcelProperty(index = 1) 19 | private String age; 20 | 21 | @ExcelProperty(index = 2) 22 | private String email; 23 | 24 | /* 25 | 作为 excel 的模型映射,需要 setter 方法 26 | */ 27 | public String getName() { 28 | return name; 29 | } 30 | 31 | public void setName(String name) { 32 | this.name = name; 33 | } 34 | 35 | public String getAge() { 36 | return age; 37 | } 38 | 39 | public void setAge(String age) { 40 | this.age = age; 41 | } 42 | 43 | public String getEmail() { 44 | return email; 45 | } 46 | 47 | public void setEmail(String email) { 48 | this.email = email; 49 | } 50 | 51 | @Override 52 | public String toString() { 53 | return "Info{" + 54 | "name='" + name + '\'' + 55 | ", age='" + age + '\'' + 56 | ", email='" + email + '\'' + 57 | '}'; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/excel/ExcelListener.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.excel; 2 | 3 | 4 | import com.alibaba.excel.context.AnalysisContext; 5 | import com.alibaba.excel.event.AnalysisEventListener; 6 | 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | /** 11 | * Created with IntelliJ IDEA 12 | * 13 | * @Author yuanhaoyue swithaoy@gmail.com 14 | * @Description 监听类,可以自定义 15 | * @Date 2018-06-05 16 | * @Time 16:58 17 | */ 18 | public class ExcelListener extends AnalysisEventListener { 19 | 20 | //自定义用于暂时存储data。 21 | //可以通过实例获取该值 22 | private List datas = new ArrayList<>(); 23 | 24 | /** 25 | * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据 26 | */ 27 | @Override 28 | public void invoke(Object object, AnalysisContext context) { 29 | //数据存储到list,供批量处理,或后续自己业务逻辑处理。 30 | datas.add(object); 31 | //根据业务自行 do something 32 | doSomething(); 33 | 34 | /* 35 | 如数据过大,可以进行定量分批处理 36 | if(datas.size()<=100){ 37 | datas.add(object); 38 | }else { 39 | doSomething(); 40 | datas = new ArrayList(); 41 | } 42 | */ 43 | 44 | } 45 | 46 | /** 47 | * 根据业务自行实现该方法 48 | */ 49 | private void doSomething() { 50 | } 51 | 52 | @Override 53 | public void doAfterAllAnalysed(AnalysisContext context) { 54 | /* 55 | datas.clear(); 56 | 解析结束销毁不用的资源 57 | */ 58 | } 59 | 60 | public List getDatas() { 61 | return datas; 62 | } 63 | 64 | public void setDatas(List datas) { 65 | this.datas = datas; 66 | } 67 | } -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/excel/ExcelWriterFactroy.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.excel; 2 | 3 | import com.alibaba.excel.ExcelWriter; 4 | import com.alibaba.excel.metadata.BaseRowModel; 5 | import com.alibaba.excel.metadata.Sheet; 6 | import com.alibaba.excel.support.ExcelTypeEnum; 7 | 8 | import java.io.IOException; 9 | import java.io.OutputStream; 10 | import java.util.List; 11 | 12 | /** 13 | * Created with IntelliJ IDEA 14 | * 15 | * @Author yuanhaoyue swithaoy@gmail.com 16 | * @Description 17 | * @Date 2018-06-07 18 | * @Time 16:47 19 | */ 20 | public class ExcelWriterFactroy extends ExcelWriter { 21 | private OutputStream outputStream; 22 | private int sheetNo = 1; 23 | 24 | public ExcelWriterFactroy(OutputStream outputStream, ExcelTypeEnum typeEnum) { 25 | super(outputStream, typeEnum); 26 | this.outputStream = outputStream; 27 | } 28 | 29 | public ExcelWriterFactroy write(List list, String sheetName, 30 | BaseRowModel object) { 31 | this.sheetNo++; 32 | try { 33 | Sheet sheet = new Sheet(sheetNo, 0, object.getClass()); 34 | sheet.setSheetName(sheetName); 35 | this.write(list, sheet); 36 | } catch (Exception ex) { 37 | ex.printStackTrace(); 38 | try { 39 | outputStream.flush(); 40 | } catch (IOException e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | return this; 45 | } 46 | 47 | @Override 48 | public void finish() { 49 | super.finish(); 50 | try { 51 | outputStream.flush(); 52 | } catch (IOException e) { 53 | e.printStackTrace(); 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 4.0.0 5 | 6 | com.howie 7 | easyexcel-method-encapsulation 8 | 0.0.1-SNAPSHOT 9 | jar 10 | 11 | easyexcel-method-encapsulation 12 | Demo project for Spring Boot 13 | 14 | 15 | org.springframework.boot 16 | spring-boot-starter-parent 17 | 1.5.6.RELEASE 18 | 19 | 20 | 21 | 22 | UTF-8 23 | UTF-8 24 | 1.8 25 | 26 | 27 | 28 | 29 | org.springframework.boot 30 | spring-boot-starter-web 31 | 32 | 33 | 34 | org.springframework.boot 35 | spring-boot-starter-test 36 | test 37 | 38 | 39 | 40 | junit 41 | junit 42 | 4.12 43 | test 44 | 45 | 46 | 47 | com.alibaba 48 | easyexcel 49 | 1.1.2-beta4 50 | 51 | 52 | 53 | 54 | 55 | 56 | org.springframework.boot 57 | spring-boot-maven-plugin 58 | 59 | 60 | 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/test/ExcelController.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.test; 2 | 3 | import com.howie.easyexcelmethodencapsulation.excel.ExcelUtil; 4 | import org.springframework.web.bind.annotation.RequestMapping; 5 | import org.springframework.web.bind.annotation.RequestMethod; 6 | import org.springframework.web.bind.annotation.RequestParam; 7 | import org.springframework.web.bind.annotation.RestController; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.IOException; 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * Created with IntelliJ IDEA 17 | * 18 | * @Author yuanhaoyue swithaoy@gmail.com 19 | * @Description 20 | * @Date 2018-06-05 21 | * @Time 16:56 22 | */ 23 | @RestController 24 | public class ExcelController { 25 | /** 26 | * 读取 Excel(允许多个 sheet) 27 | */ 28 | @RequestMapping(value = "readExcelWithSheets", method = RequestMethod.POST) 29 | public Object readExcelWithSheets(MultipartFile excel) { 30 | return ExcelUtil.readExcel(excel, new ImportInfo()); 31 | } 32 | 33 | /** 34 | * 读取 Excel(指定某个 sheet) 35 | */ 36 | @RequestMapping(value = "readExcel", method = RequestMethod.POST) 37 | public Object readExcel(MultipartFile excel, int sheetNo, 38 | @RequestParam(defaultValue = "1") int headLineNum) { 39 | return ExcelUtil.readExcel(excel, new ImportInfo(), sheetNo, headLineNum); 40 | } 41 | 42 | /** 43 | * 导出 Excel(一个 sheet) 44 | */ 45 | @RequestMapping(value = "writeExcel", method = RequestMethod.GET) 46 | public void writeExcel(HttpServletResponse response) throws IOException { 47 | List list = getList(); 48 | String fileName = "一个 Excel 文件"; 49 | String sheetName = "第一个 sheet"; 50 | 51 | ExcelUtil.writeExcel(response, list, fileName, sheetName, new ExportInfo()); 52 | } 53 | 54 | /** 55 | * 导出 Excel(多个 sheet) 56 | */ 57 | @RequestMapping(value = "writeExcelWithSheets", method = RequestMethod.GET) 58 | public void writeExcelWithSheets(HttpServletResponse response) throws IOException { 59 | List list = getList(); 60 | String fileName = "一个 Excel 文件"; 61 | String sheetName1 = "第一个 sheet"; 62 | String sheetName2 = "第二个 sheet"; 63 | String sheetName3 = "第三个 sheet"; 64 | 65 | ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName1, new ExportInfo()) 66 | .write(list, sheetName2, new ExportInfo()) 67 | .write(list, sheetName3, new ExportInfo()) 68 | .finish(); 69 | } 70 | 71 | private List getList() { 72 | List list = new ArrayList<>(); 73 | ExportInfo model1 = new ExportInfo(); 74 | model1.setName("howie"); 75 | model1.setAge("19"); 76 | model1.setAddress("123456789"); 77 | model1.setEmail("123456789@gmail.com"); 78 | list.add(model1); 79 | ExportInfo model2 = new ExportInfo(); 80 | model2.setName("harry"); 81 | model2.setAge("20"); 82 | model2.setAddress("198752233"); 83 | model2.setEmail("198752233@gmail.com"); 84 | list.add(model2); 85 | return list; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /mvnw.cmd: -------------------------------------------------------------------------------- 1 | @REM ---------------------------------------------------------------------------- 2 | @REM Licensed to the Apache Software Foundation (ASF) under one 3 | @REM or more contributor license agreements. See the NOTICE file 4 | @REM distributed with this work for additional information 5 | @REM regarding copyright ownership. The ASF licenses this file 6 | @REM to you under the Apache License, Version 2.0 (the 7 | @REM "License"); you may not use this file except in compliance 8 | @REM with the License. You may obtain a copy of the License at 9 | @REM 10 | @REM http://www.apache.org/licenses/LICENSE-2.0 11 | @REM 12 | @REM Unless required by applicable law or agreed to in writing, 13 | @REM software distributed under the License is distributed on an 14 | @REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | @REM KIND, either express or implied. See the License for the 16 | @REM specific language governing permissions and limitations 17 | @REM under the License. 18 | @REM ---------------------------------------------------------------------------- 19 | 20 | @REM ---------------------------------------------------------------------------- 21 | @REM Maven2 Start Up Batch script 22 | @REM 23 | @REM Required ENV vars: 24 | @REM JAVA_HOME - location of a JDK home dir 25 | @REM 26 | @REM Optional ENV vars 27 | @REM M2_HOME - location of maven2's installed home dir 28 | @REM MAVEN_BATCH_ECHO - set to 'on' to enable the echoing of the batch commands 29 | @REM MAVEN_BATCH_PAUSE - set to 'on' to wait for a key stroke before ending 30 | @REM MAVEN_OPTS - parameters passed to the Java VM when running Maven 31 | @REM e.g. to debug Maven itself, use 32 | @REM set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 33 | @REM MAVEN_SKIP_RC - flag to disable loading of mavenrc files 34 | @REM ---------------------------------------------------------------------------- 35 | 36 | @REM Begin all REM lines with '@' in case MAVEN_BATCH_ECHO is 'on' 37 | @echo off 38 | @REM enable echoing my setting MAVEN_BATCH_ECHO to 'on' 39 | @if "%MAVEN_BATCH_ECHO%" == "on" echo %MAVEN_BATCH_ECHO% 40 | 41 | @REM set %HOME% to equivalent of $HOME 42 | if "%HOME%" == "" (set "HOME=%HOMEDRIVE%%HOMEPATH%") 43 | 44 | @REM Execute a user defined script before this one 45 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPre 46 | @REM check for pre script, once with legacy .bat ending and once with .cmd ending 47 | if exist "%HOME%\mavenrc_pre.bat" call "%HOME%\mavenrc_pre.bat" 48 | if exist "%HOME%\mavenrc_pre.cmd" call "%HOME%\mavenrc_pre.cmd" 49 | :skipRcPre 50 | 51 | @setlocal 52 | 53 | set ERROR_CODE=0 54 | 55 | @REM To isolate internal variables from possible post scripts, we use another setlocal 56 | @setlocal 57 | 58 | @REM ==== START VALIDATION ==== 59 | if not "%JAVA_HOME%" == "" goto OkJHome 60 | 61 | echo. 62 | echo Error: JAVA_HOME not found in your environment. >&2 63 | echo Please set the JAVA_HOME variable in your environment to match the >&2 64 | echo location of your Java installation. >&2 65 | echo. 66 | goto error 67 | 68 | :OkJHome 69 | if exist "%JAVA_HOME%\bin\java.exe" goto init 70 | 71 | echo. 72 | echo Error: JAVA_HOME is set to an invalid directory. >&2 73 | echo JAVA_HOME = "%JAVA_HOME%" >&2 74 | echo Please set the JAVA_HOME variable in your environment to match the >&2 75 | echo location of your Java installation. >&2 76 | echo. 77 | goto error 78 | 79 | @REM ==== END VALIDATION ==== 80 | 81 | :init 82 | 83 | @REM Find the project base dir, i.e. the directory that contains the folder ".mvn". 84 | @REM Fallback to current working directory if not found. 85 | 86 | set MAVEN_PROJECTBASEDIR=%MAVEN_BASEDIR% 87 | IF NOT "%MAVEN_PROJECTBASEDIR%"=="" goto endDetectBaseDir 88 | 89 | set EXEC_DIR=%CD% 90 | set WDIR=%EXEC_DIR% 91 | :findBaseDir 92 | IF EXIST "%WDIR%"\.mvn goto baseDirFound 93 | cd .. 94 | IF "%WDIR%"=="%CD%" goto baseDirNotFound 95 | set WDIR=%CD% 96 | goto findBaseDir 97 | 98 | :baseDirFound 99 | set MAVEN_PROJECTBASEDIR=%WDIR% 100 | cd "%EXEC_DIR%" 101 | goto endDetectBaseDir 102 | 103 | :baseDirNotFound 104 | set MAVEN_PROJECTBASEDIR=%EXEC_DIR% 105 | cd "%EXEC_DIR%" 106 | 107 | :endDetectBaseDir 108 | 109 | IF NOT EXIST "%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config" goto endReadAdditionalConfig 110 | 111 | @setlocal EnableExtensions EnableDelayedExpansion 112 | for /F "usebackq delims=" %%a in ("%MAVEN_PROJECTBASEDIR%\.mvn\jvm.config") do set JVM_CONFIG_MAVEN_PROPS=!JVM_CONFIG_MAVEN_PROPS! %%a 113 | @endlocal & set JVM_CONFIG_MAVEN_PROPS=%JVM_CONFIG_MAVEN_PROPS% 114 | 115 | :endReadAdditionalConfig 116 | 117 | SET MAVEN_JAVA_EXE="%JAVA_HOME%\bin\java.exe" 118 | 119 | set WRAPPER_JAR="%MAVEN_PROJECTBASEDIR%\.mvn\wrapper\maven-wrapper.jar" 120 | set WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 121 | 122 | %MAVEN_JAVA_EXE% %JVM_CONFIG_MAVEN_PROPS% %MAVEN_OPTS% %MAVEN_DEBUG_OPTS% -classpath %WRAPPER_JAR% "-Dmaven.multiModuleProjectDirectory=%MAVEN_PROJECTBASEDIR%" %WRAPPER_LAUNCHER% %MAVEN_CONFIG% %* 123 | if ERRORLEVEL 1 goto error 124 | goto end 125 | 126 | :error 127 | set ERROR_CODE=1 128 | 129 | :end 130 | @endlocal & set ERROR_CODE=%ERROR_CODE% 131 | 132 | if not "%MAVEN_SKIP_RC%" == "" goto skipRcPost 133 | @REM check for post script, once with legacy .bat ending and once with .cmd ending 134 | if exist "%HOME%\mavenrc_post.bat" call "%HOME%\mavenrc_post.bat" 135 | if exist "%HOME%\mavenrc_post.cmd" call "%HOME%\mavenrc_post.cmd" 136 | :skipRcPost 137 | 138 | @REM pause the script if MAVEN_BATCH_PAUSE is set to 'on' 139 | if "%MAVEN_BATCH_PAUSE%" == "on" pause 140 | 141 | if "%MAVEN_TERMINATE_CMD%" == "on" exit %ERROR_CODE% 142 | 143 | exit /B %ERROR_CODE% 144 | -------------------------------------------------------------------------------- /src/main/java/com/howie/easyexcelmethodencapsulation/excel/ExcelUtil.java: -------------------------------------------------------------------------------- 1 | package com.howie.easyexcelmethodencapsulation.excel; 2 | 3 | import com.alibaba.excel.ExcelReader; 4 | import com.alibaba.excel.ExcelWriter; 5 | import com.alibaba.excel.metadata.BaseRowModel; 6 | import com.alibaba.excel.metadata.Sheet; 7 | import com.alibaba.excel.support.ExcelTypeEnum; 8 | import org.springframework.web.multipart.MultipartFile; 9 | 10 | import javax.servlet.http.HttpServletResponse; 11 | import java.io.*; 12 | import java.util.List; 13 | 14 | /** 15 | * Created with IntelliJ IDEA 16 | * 17 | * @Author yuanhaoyue swithaoy@gmail.com 18 | * @Description 工具类 19 | * @Date 2018-06-06 20 | * @Time 14:07 21 | */ 22 | public class ExcelUtil { 23 | /** 24 | * 读取 Excel(多个 sheet) 25 | * 26 | * @param excel 文件 27 | * @param rowModel 实体类映射,继承 BaseRowModel 类 28 | * @return Excel 数据 list 29 | */ 30 | public static List readExcel(MultipartFile excel, BaseRowModel rowModel) { 31 | ExcelListener excelListener = new ExcelListener(); 32 | ExcelReader reader = getReader(excel, excelListener); 33 | if (reader == null) { 34 | return null; 35 | } 36 | for (Sheet sheet : reader.getSheets()) { 37 | if (rowModel != null) { 38 | sheet.setClazz(rowModel.getClass()); 39 | } 40 | reader.read(sheet); 41 | } 42 | return excelListener.getDatas(); 43 | } 44 | 45 | /** 46 | * 读取某个 sheet 的 Excel 47 | * 48 | * @param excel 文件 49 | * @param rowModel 实体类映射,继承 BaseRowModel 类 50 | * @param sheetNo sheet 的序号 从1开始 51 | * @return Excel 数据 list 52 | */ 53 | public static List readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo) { 54 | return readExcel(excel, rowModel, sheetNo, 1); 55 | } 56 | 57 | /** 58 | * 读取某个 sheet 的 Excel 59 | * 60 | * @param excel 文件 61 | * @param rowModel 实体类映射,继承 BaseRowModel 类 62 | * @param sheetNo sheet 的序号 从1开始 63 | * @param headLineNum 表头行数,默认为1 64 | * @return Excel 数据 list 65 | */ 66 | public static List readExcel(MultipartFile excel, BaseRowModel rowModel, int sheetNo, 67 | int headLineNum) { 68 | ExcelListener excelListener = new ExcelListener(); 69 | ExcelReader reader = getReader(excel, excelListener); 70 | if (reader == null) { 71 | return null; 72 | } 73 | reader.read(new Sheet(sheetNo, headLineNum, rowModel.getClass())); 74 | return excelListener.getDatas(); 75 | } 76 | 77 | /** 78 | * 导出 Excel :一个 sheet,带表头 79 | * 80 | * @param response HttpServletResponse 81 | * @param list 数据 list,每个元素为一个 BaseRowModel 82 | * @param fileName 导出的文件名 83 | * @param sheetName 导入文件的 sheet 名 84 | * @param object 映射实体类,Excel 模型 85 | */ 86 | public static void writeExcel(HttpServletResponse response, List list, 87 | String fileName, String sheetName, BaseRowModel object) { 88 | ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX); 89 | Sheet sheet = new Sheet(1, 0, object.getClass()); 90 | sheet.setSheetName(sheetName); 91 | writer.write(list, sheet); 92 | writer.finish(); 93 | } 94 | 95 | /** 96 | * 导出 Excel :多个 sheet,带表头 97 | * 98 | * @param response HttpServletResponse 99 | * @param list 数据 list,每个元素为一个 BaseRowModel 100 | * @param fileName 导出的文件名 101 | * @param sheetName 导入文件的 sheet 名 102 | * @param object 映射实体类,Excel 模型 103 | */ 104 | public static ExcelWriterFactroy writeExcelWithSheets(HttpServletResponse response, List list, 105 | String fileName, String sheetName, BaseRowModel object) { 106 | ExcelWriterFactroy writer = new ExcelWriterFactroy(getOutputStream(fileName, response), ExcelTypeEnum.XLSX); 107 | Sheet sheet = new Sheet(1, 0, object.getClass()); 108 | sheet.setSheetName(sheetName); 109 | writer.write(list, sheet); 110 | return writer; 111 | } 112 | 113 | /** 114 | * 导出文件时为Writer生成OutputStream 115 | */ 116 | private static OutputStream getOutputStream(String fileName, HttpServletResponse response) { 117 | //创建本地文件 118 | String filePath = fileName + ".xlsx"; 119 | File dbfFile = new File(filePath); 120 | try { 121 | if (!dbfFile.exists() || dbfFile.isDirectory()) { 122 | dbfFile.createNewFile(); 123 | } 124 | fileName = new String(filePath.getBytes(), "ISO-8859-1"); 125 | response.addHeader("Content-Disposition", "filename=" + fileName); 126 | return response.getOutputStream(); 127 | } catch (IOException e) { 128 | throw new ExcelException("创建文件失败!"); 129 | } 130 | } 131 | 132 | /** 133 | * 返回 ExcelReader 134 | * 135 | * @param excel 需要解析的 Excel 文件 136 | * @param excelListener new ExcelListener() 137 | */ 138 | private static ExcelReader getReader(MultipartFile excel, 139 | ExcelListener excelListener) { 140 | String filename = excel.getOriginalFilename(); 141 | if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) { 142 | throw new ExcelException("文件格式错误!"); 143 | } 144 | InputStream inputStream; 145 | try { 146 | inputStream = new BufferedInputStream(excel.getInputStream()); 147 | return new ExcelReader(inputStream, null, excelListener, false); 148 | } catch (IOException e) { 149 | e.printStackTrace(); 150 | } 151 | return null; 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # easyexcel-encapsulation 2 | easyexcel 项目地址 :https://github.com/alibaba/easyexcel 3 | 4 | #### 对 easyexcel 进行了方法的封装,可以做到一个函数完成简单的读取和导出 5 | 6 | #### 目前 easyexcel 版本已经更新至 1.1.2-beta4 7 | 8 | --- 9 | 10 | # 一. 依赖 11 | 首先是添加该项目的依赖,目前的版本是 1.1.2-beta4 12 | ``` 13 | 14 | com.alibaba 15 | easyexcel 16 | 1.1.2-beta4 17 | 18 | ``` 19 | 20 | # 二. 需要的类 21 | ![](https://upload-images.jianshu.io/upload_images/8807674-5fe0519ac2597f96.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 22 | 23 | ## 1. ExcelUtil 24 | 工具类,可以直接调用该工具类的方法完成 Excel 的读或者写 25 | 26 | ## 2. ExcelListener 27 | 监听类,可以根据需要,自定义处理获取到的数据 28 | ``` 29 | public class ExcelListener extends AnalysisEventListener { 30 | 31 | //自定义用于暂时存储data。 32 | //可以通过实例获取该值 33 | private List datas = new ArrayList<>(); 34 | 35 | /** 36 | * 通过 AnalysisContext 对象还可以获取当前 sheet,当前行等数据 37 | */ 38 | @Override 39 | public void invoke(Object object, AnalysisContext context) { 40 | //数据存储到list,供批量处理,或后续自己业务逻辑处理。 41 | datas.add(object); 42 | //根据自己业务做处理 43 | doSomething(object); 44 | } 45 | 46 | private void doSomething(Object object) { 47 | } 48 | 49 | @Override 50 | public void doAfterAllAnalysed(AnalysisContext context) { 51 | /* 52 | datas.clear(); 53 | 解析结束销毁不用的资源 54 | */ 55 | } 56 | 57 | public List getDatas() { 58 | return datas; 59 | } 60 | 61 | public void setDatas(List datas) { 62 | this.datas = datas; 63 | } 64 | } 65 | ``` 66 | 67 | ## 3. ExcelWriterFactroy 68 | 用于导出多个 sheet 的 Excel,通过多次调用 write 方法写入多个 sheet 69 | 70 | ## 4. ExcelException 71 | 捕获相关 Exception 72 | 73 | # 三. 读取 Excel 74 | 读取 Excel 时只需要调用 ```ExcelUtil.readExcel()``` 方法 75 | ``` 76 | @RequestMapping(value = "readExcel", method = RequestMethod.POST) 77 | public Object readExcel(MultipartFile excel) { 78 | return ExcelUtil.readExcel(excel, new ImportInfo()); 79 | } 80 | ``` 81 | 82 | 其中 excel 是 MultipartFile 类型的文件对象,而 new ImportInfo() 是该 Excel 所映射的实体对象,需要继承 **BaseRowModel** 类,如: 83 | ``` 84 | public class ImportInfo extends BaseRowModel { 85 | @ExcelProperty(index = 0) 86 | private String name; 87 | 88 | @ExcelProperty(index = 1) 89 | private String age; 90 | 91 | @ExcelProperty(index = 2) 92 | private String email; 93 | 94 | /* 95 | 作为 excel 的模型映射,需要 setter 方法 96 | */ 97 | public String getName() { 98 | return name; 99 | } 100 | 101 | public void setName(String name) { 102 | this.name = name; 103 | } 104 | 105 | public String getAge() { 106 | return age; 107 | } 108 | 109 | public void setAge(String age) { 110 | this.age = age; 111 | } 112 | 113 | public String getEmail() { 114 | return email; 115 | } 116 | 117 | public void setEmail(String email) { 118 | this.email = email; 119 | } 120 | } 121 | ``` 122 | 作为映射实体类,通过 @ExcelProperty 注解与 index 变量可以标注成员变量所映射的列,同时不可缺少 setter 方法 123 | 124 | 125 | 126 | # 四. 导出 Excel 127 | ### 1. 导出的 Excel 只拥有一个 sheet 128 | 只需要调用 ```ExcelUtil.writeExcelWithSheets()``` 方法: 129 | ``` 130 | @RequestMapping(value = "writeExcel", method = RequestMethod.GET) 131 | public void writeExcel(HttpServletResponse response) throws IOException { 132 | List list = getList(); 133 | String fileName = "一个 Excel 文件"; 134 | String sheetName = "第一个 sheet"; 135 | 136 | ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName, new ExportInfo()); 137 | } 138 | ``` 139 | fileName,sheetName 分别是导出文件的文件名和 sheet 名,new ExportInfo() 为导出数据的映射实体对象,list 为导出数据。 140 | 141 | 对于映射实体类,可以根据需要通过 @ExcelProperty 注解自定义表头,当然同样需要继承 BaseRowModel 类,如: 142 | ``` 143 | public class ExportInfo extends BaseRowModel { 144 | @ExcelProperty(value = "姓名" ,index = 0) 145 | private String name; 146 | 147 | @ExcelProperty(value = "年龄",index = 1) 148 | private String age; 149 | 150 | @ExcelProperty(value = "邮箱",index = 2) 151 | private String email; 152 | 153 | @ExcelProperty(value = "地址",index = 3) 154 | private String address; 155 | } 156 | ``` 157 | value 为列名,index 为列的序号 158 | 159 | 如果需要复杂一点,可以实现如下图的效果: 160 | ![](https://upload-images.jianshu.io/upload_images/8807674-5cb70346428fea93.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 161 | 162 | 对应的实体类写法如下: 163 | ``` 164 | public class MultiLineHeadExcelModel extends BaseRowModel { 165 | 166 | @ExcelProperty(value = {"表头1","表头1","表头31"},index = 0) 167 | private String p1; 168 | 169 | @ExcelProperty(value = {"表头1","表头1","表头32"},index = 1) 170 | private String p2; 171 | 172 | @ExcelProperty(value = {"表头3","表头3","表头3"},index = 2) 173 | private int p3; 174 | 175 | @ExcelProperty(value = {"表头4","表头4","表头4"},index = 3) 176 | private long p4; 177 | 178 | @ExcelProperty(value = {"表头5","表头51","表头52"},index = 4) 179 | private String p5; 180 | 181 | @ExcelProperty(value = {"表头6","表头61","表头611"},index = 5) 182 | private String p6; 183 | 184 | @ExcelProperty(value = {"表头6","表头61","表头612"},index = 6) 185 | private String p7; 186 | 187 | @ExcelProperty(value = {"表头6","表头62","表头621"},index = 7) 188 | private String p8; 189 | 190 | @ExcelProperty(value = {"表头6","表头62","表头622"},index = 8) 191 | private String p9; 192 | } 193 | ``` 194 | ### 2. 导出的 Excel 拥有多个 sheet 195 | 调用 ```ExcelUtil.writeExcelWithSheets()``` 处理第一个 sheet,之后调用 ```write()``` 方法依次处理之后的 sheet,最后使用 ```finish()``` 方法结束 196 | ``` 197 | public void writeExcelWithSheets(HttpServletResponse response) throws IOException { 198 | List list = getList(); 199 | String fileName = "一个 Excel 文件"; 200 | String sheetName1 = "第一个 sheet"; 201 | String sheetName2 = "第二个 sheet"; 202 | String sheetName3 = "第三个 sheet"; 203 | 204 | ExcelUtil.writeExcelWithSheets(response, list, fileName, sheetName1, new ExportInfo()) 205 | .write(list, sheetName2, new ExportInfo()) 206 | .write(list, sheetName3, new ExportInfo()) 207 | .finish(); 208 | } 209 | ``` 210 | write 方法的参数为当前 sheet 的 list 数据,当前 sheet 名以及对应的映射类 211 | 212 | -------------------------------------------------------------------------------- /mvnw: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # ---------------------------------------------------------------------------- 3 | # Licensed to the Apache Software Foundation (ASF) under one 4 | # or more contributor license agreements. See the NOTICE file 5 | # distributed with this work for additional information 6 | # regarding copyright ownership. The ASF licenses this file 7 | # to you under the Apache License, Version 2.0 (the 8 | # "License"); you may not use this file except in compliance 9 | # with the License. You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, 14 | # software distributed under the License is distributed on an 15 | # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 16 | # KIND, either express or implied. See the License for the 17 | # specific language governing permissions and limitations 18 | # under the License. 19 | # ---------------------------------------------------------------------------- 20 | 21 | # ---------------------------------------------------------------------------- 22 | # Maven2 Start Up Batch script 23 | # 24 | # Required ENV vars: 25 | # ------------------ 26 | # JAVA_HOME - location of a JDK home dir 27 | # 28 | # Optional ENV vars 29 | # ----------------- 30 | # M2_HOME - location of maven2's installed home dir 31 | # MAVEN_OPTS - parameters passed to the Java VM when running Maven 32 | # e.g. to debug Maven itself, use 33 | # set MAVEN_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000 34 | # MAVEN_SKIP_RC - flag to disable loading of mavenrc files 35 | # ---------------------------------------------------------------------------- 36 | 37 | if [ -z "$MAVEN_SKIP_RC" ] ; then 38 | 39 | if [ -f /etc/mavenrc ] ; then 40 | . /etc/mavenrc 41 | fi 42 | 43 | if [ -f "$HOME/.mavenrc" ] ; then 44 | . "$HOME/.mavenrc" 45 | fi 46 | 47 | fi 48 | 49 | # OS specific support. $var _must_ be set to either true or false. 50 | cygwin=false; 51 | darwin=false; 52 | mingw=false 53 | case "`uname`" in 54 | CYGWIN*) cygwin=true ;; 55 | MINGW*) mingw=true;; 56 | Darwin*) darwin=true 57 | # Use /usr/libexec/java_home if available, otherwise fall back to /Library/Java/Home 58 | # See https://developer.apple.com/library/mac/qa/qa1170/_index.html 59 | if [ -z "$JAVA_HOME" ]; then 60 | if [ -x "/usr/libexec/java_home" ]; then 61 | export JAVA_HOME="`/usr/libexec/java_home`" 62 | else 63 | export JAVA_HOME="/Library/Java/Home" 64 | fi 65 | fi 66 | ;; 67 | esac 68 | 69 | if [ -z "$JAVA_HOME" ] ; then 70 | if [ -r /etc/gentoo-release ] ; then 71 | JAVA_HOME=`java-config --jre-home` 72 | fi 73 | fi 74 | 75 | if [ -z "$M2_HOME" ] ; then 76 | ## resolve links - $0 may be a link to maven's home 77 | PRG="$0" 78 | 79 | # need this for relative symlinks 80 | while [ -h "$PRG" ] ; do 81 | ls=`ls -ld "$PRG"` 82 | link=`expr "$ls" : '.*-> \(.*\)$'` 83 | if expr "$link" : '/.*' > /dev/null; then 84 | PRG="$link" 85 | else 86 | PRG="`dirname "$PRG"`/$link" 87 | fi 88 | done 89 | 90 | saveddir=`pwd` 91 | 92 | M2_HOME=`dirname "$PRG"`/.. 93 | 94 | # make it fully qualified 95 | M2_HOME=`cd "$M2_HOME" && pwd` 96 | 97 | cd "$saveddir" 98 | # echo Using m2 at $M2_HOME 99 | fi 100 | 101 | # For Cygwin, ensure paths are in UNIX format before anything is touched 102 | if $cygwin ; then 103 | [ -n "$M2_HOME" ] && 104 | M2_HOME=`cygpath --unix "$M2_HOME"` 105 | [ -n "$JAVA_HOME" ] && 106 | JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 107 | [ -n "$CLASSPATH" ] && 108 | CLASSPATH=`cygpath --path --unix "$CLASSPATH"` 109 | fi 110 | 111 | # For Migwn, ensure paths are in UNIX format before anything is touched 112 | if $mingw ; then 113 | [ -n "$M2_HOME" ] && 114 | M2_HOME="`(cd "$M2_HOME"; pwd)`" 115 | [ -n "$JAVA_HOME" ] && 116 | JAVA_HOME="`(cd "$JAVA_HOME"; pwd)`" 117 | # TODO classpath? 118 | fi 119 | 120 | if [ -z "$JAVA_HOME" ]; then 121 | javaExecutable="`which javac`" 122 | if [ -n "$javaExecutable" ] && ! [ "`expr \"$javaExecutable\" : '\([^ ]*\)'`" = "no" ]; then 123 | # readlink(1) is not available as standard on Solaris 10. 124 | readLink=`which readlink` 125 | if [ ! `expr "$readLink" : '\([^ ]*\)'` = "no" ]; then 126 | if $darwin ; then 127 | javaHome="`dirname \"$javaExecutable\"`" 128 | javaExecutable="`cd \"$javaHome\" && pwd -P`/javac" 129 | else 130 | javaExecutable="`readlink -f \"$javaExecutable\"`" 131 | fi 132 | javaHome="`dirname \"$javaExecutable\"`" 133 | javaHome=`expr "$javaHome" : '\(.*\)/bin'` 134 | JAVA_HOME="$javaHome" 135 | export JAVA_HOME 136 | fi 137 | fi 138 | fi 139 | 140 | if [ -z "$JAVACMD" ] ; then 141 | if [ -n "$JAVA_HOME" ] ; then 142 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 143 | # IBM's JDK on AIX uses strange locations for the executables 144 | JAVACMD="$JAVA_HOME/jre/sh/java" 145 | else 146 | JAVACMD="$JAVA_HOME/bin/java" 147 | fi 148 | else 149 | JAVACMD="`which java`" 150 | fi 151 | fi 152 | 153 | if [ ! -x "$JAVACMD" ] ; then 154 | echo "Error: JAVA_HOME is not defined correctly." >&2 155 | echo " We cannot execute $JAVACMD" >&2 156 | exit 1 157 | fi 158 | 159 | if [ -z "$JAVA_HOME" ] ; then 160 | echo "Warning: JAVA_HOME environment variable is not set." 161 | fi 162 | 163 | CLASSWORLDS_LAUNCHER=org.codehaus.plexus.classworlds.launcher.Launcher 164 | 165 | # traverses directory structure from process work directory to filesystem root 166 | # first directory with .mvn subdirectory is considered project base directory 167 | find_maven_basedir() { 168 | 169 | if [ -z "$1" ] 170 | then 171 | echo "Path not specified to find_maven_basedir" 172 | return 1 173 | fi 174 | 175 | basedir="$1" 176 | wdir="$1" 177 | while [ "$wdir" != '/' ] ; do 178 | if [ -d "$wdir"/.mvn ] ; then 179 | basedir=$wdir 180 | break 181 | fi 182 | # workaround for JBEAP-8937 (on Solaris 10/Sparc) 183 | if [ -d "${wdir}" ]; then 184 | wdir=`cd "$wdir/.."; pwd` 185 | fi 186 | # end of workaround 187 | done 188 | echo "${basedir}" 189 | } 190 | 191 | # concatenates all lines of a file 192 | concat_lines() { 193 | if [ -f "$1" ]; then 194 | echo "$(tr -s '\n' ' ' < "$1")" 195 | fi 196 | } 197 | 198 | BASE_DIR=`find_maven_basedir "$(pwd)"` 199 | if [ -z "$BASE_DIR" ]; then 200 | exit 1; 201 | fi 202 | 203 | export MAVEN_PROJECTBASEDIR=${MAVEN_BASEDIR:-"$BASE_DIR"} 204 | echo $MAVEN_PROJECTBASEDIR 205 | MAVEN_OPTS="$(concat_lines "$MAVEN_PROJECTBASEDIR/.mvn/jvm.config") $MAVEN_OPTS" 206 | 207 | # For Cygwin, switch paths to Windows format before running java 208 | if $cygwin; then 209 | [ -n "$M2_HOME" ] && 210 | M2_HOME=`cygpath --path --windows "$M2_HOME"` 211 | [ -n "$JAVA_HOME" ] && 212 | JAVA_HOME=`cygpath --path --windows "$JAVA_HOME"` 213 | [ -n "$CLASSPATH" ] && 214 | CLASSPATH=`cygpath --path --windows "$CLASSPATH"` 215 | [ -n "$MAVEN_PROJECTBASEDIR" ] && 216 | MAVEN_PROJECTBASEDIR=`cygpath --path --windows "$MAVEN_PROJECTBASEDIR"` 217 | fi 218 | 219 | WRAPPER_LAUNCHER=org.apache.maven.wrapper.MavenWrapperMain 220 | 221 | exec "$JAVACMD" \ 222 | $MAVEN_OPTS \ 223 | -classpath "$MAVEN_PROJECTBASEDIR/.mvn/wrapper/maven-wrapper.jar" \ 224 | "-Dmaven.home=${M2_HOME}" "-Dmaven.multiModuleProjectDirectory=${MAVEN_PROJECTBASEDIR}" \ 225 | ${WRAPPER_LAUNCHER} $MAVEN_CONFIG "$@" 226 | --------------------------------------------------------------------------------