├── .gitignore ├── 关系.png ├── 实体类.png ├── 引用.png ├── 效果_.png ├── 测试.xls ├── 测试.xlsx ├── Save.xlsx ├── write.png ├── SaveMap.xlsx ├── 关系(old).png ├── 关系(old_01).png ├── jetbrains-variant-3.png ├── src ├── main │ └── java │ │ └── seven │ │ ├── handler │ │ ├── InPutHandler.java │ │ ├── implInput │ │ │ ├── LongHandler.java │ │ │ ├── DoubleHandler.java │ │ │ ├── IntegerHandler.java │ │ │ ├── LocalDateHandler.java │ │ │ └── LocalDateTimeHandler.java │ │ ├── OutPutHandler.java │ │ ├── implOutput │ │ │ ├── BaseOutPutHandler.java │ │ │ └── LocalDateTimeHandler.java │ │ └── HandlerFactory.java │ │ ├── callBack │ │ ├── DataFilterProcessInterface.java │ │ ├── DataFilterInterface.java │ │ ├── imp │ │ │ ├── DefaultDataFilter.java │ │ │ ├── DefaultDateColFilter.java │ │ │ ├── DefaultDataProFilter.java │ │ │ └── DefaultConvert.java │ │ ├── DataFilterColumnInterface.java │ │ ├── ConvertInterface.java │ │ ├── CellStyleInterface.java │ │ ├── PackageDataInterface.java │ │ └── CellStyleCallbackWrapper.java │ │ ├── wapperInt │ │ ├── ReaderObj.java │ │ ├── ReaderMap.java │ │ ├── wapperRef │ │ │ ├── WrapperObj.java │ │ │ ├── WrapperMap.java │ │ │ └── sysWppers │ │ │ │ ├── ResWrapperMap.java │ │ │ │ └── ResWrapperObj.java │ │ └── Wrapper.java │ │ ├── anno │ │ └── ExcelAnno.java │ │ ├── ExcelSuperInterface.java │ │ ├── savewapper │ │ ├── wapperRef │ │ │ ├── sysWppers │ │ │ │ ├── ResExportDBMap.java │ │ │ │ ├── ResExportDBObj.java │ │ │ │ ├── ResExportMap.java │ │ │ │ └── ResExportObj.java │ │ │ └── SaveExcelObject.java │ │ ├── SaveExcel.java │ │ └── cellStyle │ │ │ └── CellStyle.java │ │ ├── util │ │ ├── RegHelper.java │ │ └── ExcelTool.java │ │ ├── config │ │ └── Config.java │ │ └── ExcelFactory.java └── test │ └── java │ ├── ConvertTest.java │ ├── B.java │ └── Demo.java ├── UPDATELOG.MD ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .idea -------------------------------------------------------------------------------- /关系.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/关系.png -------------------------------------------------------------------------------- /实体类.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/实体类.png -------------------------------------------------------------------------------- /引用.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/引用.png -------------------------------------------------------------------------------- /效果_.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/效果_.png -------------------------------------------------------------------------------- /测试.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/测试.xls -------------------------------------------------------------------------------- /测试.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/测试.xlsx -------------------------------------------------------------------------------- /Save.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/Save.xlsx -------------------------------------------------------------------------------- /write.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/write.png -------------------------------------------------------------------------------- /SaveMap.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/SaveMap.xlsx -------------------------------------------------------------------------------- /关系(old).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/关系(old).png -------------------------------------------------------------------------------- /关系(old_01).png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/关系(old_01).png -------------------------------------------------------------------------------- /jetbrains-variant-3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MatrixSeven/ExcelReads/HEAD/jetbrains-variant-3.png -------------------------------------------------------------------------------- /src/main/java/seven/handler/InPutHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler; 2 | 3 | public interface InPutHandler { 4 | default T Handler(String source) { 5 | if (source != null && !"".equals(source)) { 6 | return handlerConvert(source); 7 | } 8 | return null; 9 | } 10 | 11 | T handlerConvert(String source); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/DataFilterProcessInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | 3 | 4 | import java.util.function.Consumer; 5 | 6 | /** 7 | * [Github]https://github.com/MatrixSeven 8 | * [Bolg]https://matrixseven.github.io/ 9 | * Created by seven on 2016/10/18. 10 | * 此处传入每一行打包好的数据。对应一个实体 11 | * T为实体Bean类型 12 | */ 13 | @FunctionalInterface 14 | public interface DataFilterProcessInterface extends Consumer { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/DataFilterInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | 3 | import java.util.function.Predicate; 4 | 5 | /** 6 | * [Github]https://github.com/MatrixSeven 7 | * [Bolg]https://matrixseven.github.io/ 8 | * Created by seven on 2016/10/18. 9 | * 对要包装的数据进行过滤,对应实体Bean,如果返回false将放弃此条数据 10 | * T为实体Bean类型 11 | */ 12 | @FunctionalInterface 13 | public interface DataFilterInterface extends Predicate { 14 | 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/imp/DefaultDataFilter.java: -------------------------------------------------------------------------------- 1 | package seven.callBack.imp; 2 | 3 | import seven.callBack.DataFilterInterface; 4 | 5 | /** 6 | * [Github]https://github.com/MatrixSeven 7 | * [Bolg]https://matrixseven.github.io/ 8 | * Created by seven on 2016/10/18. 9 | */ 10 | public class DefaultDataFilter implements DataFilterInterface{ 11 | @Override 12 | public boolean test(T o) { 13 | return true; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/DataFilterColumnInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | 3 | /** 4 | * [Github]https://github.com/MatrixSeven 5 | * [Bolg]https://matrixseven.github.io/ 6 | * Created by seven on 2016/10/19. 7 | * *{@link seven.savewapper.SaveExcel} 8 | */ 9 | @FunctionalInterface 10 | public interface DataFilterColumnInterface { 11 | /** 12 | *{@link seven.savewapper.SaveExcel} 13 | * @return String[] 14 | */ 15 | String[] filter(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/imp/DefaultDateColFilter.java: -------------------------------------------------------------------------------- 1 | package seven.callBack.imp; 2 | 3 | import seven.callBack.DataFilterColumnInterface; 4 | 5 | /** 6 | * [Github]https://github.com/MatrixSeven 7 | * [Bolg]https://matrixseven.github.io/ 8 | * Created by seven on 2016/10/19. 9 | */ 10 | public class DefaultDateColFilter implements DataFilterColumnInterface { 11 | 12 | @Override 13 | public String[] filter() { 14 | return new String[0]; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/imp/DefaultDataProFilter.java: -------------------------------------------------------------------------------- 1 | package seven.callBack.imp; 2 | 3 | import org.apache.poi.ss.formula.functions.T; 4 | import seven.callBack.DataFilterProcessInterface; 5 | 6 | /** 7 | * [Github]https://github.com/MatrixSeven 8 | * [Bolg]https://matrixseven.github.io/ 9 | * Created by seven on 2016/10/18. 10 | */ 11 | @SuppressWarnings("unchecked") 12 | public class DefaultDataProFilter implements DataFilterProcessInterface { 13 | 14 | @Override 15 | public void accept(T o) { 16 | 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/ConvertInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | /** 20 | * @author Seven 21 | * FileName: FiledConvert.java 22 | * Created by Seven on 2019/12/2 23 | **/ 24 | @FunctionalInterface 25 | public interface ConvertInterface { 26 | T convert(Object o); 27 | } 28 | 29 | -------------------------------------------------------------------------------- /src/test/java/ConvertTest.java: -------------------------------------------------------------------------------- 1 | //======================================================= 2 | // .----. 3 | // _.'__ `. 4 | // .--(^)(^^)---/!\ 5 | // .' @ /!!!\ 6 | // : , !!!! 7 | // `-..__.-' _.-\!!!/ 8 | // `;_: `"' 9 | // .'"""""`. 10 | // /, ya ,\\ 11 | // //狗神保佑\\ 12 | // `-._______.-' 13 | // ___`. | .'___ 14 | // (______|______) 15 | //======================================================= 16 | 17 | import seven.callBack.ConvertInterface; 18 | 19 | /** 20 | * @author Seven 21 | * FileName: ConverTest.java 22 | * Created by Seven on 2019/12/2 23 | **/ 24 | public class ConvertTest implements ConvertInterface { 25 | @Override 26 | public String convert(Object o) { 27 | return o.toString()+o.toString(); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/CellStyleInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import seven.savewapper.cellStyle.CellStyle; 19 | 20 | /** 21 | * [Zhihu]https://www.zhihu.com/people/Sweets07 22 | * [Github]https://github.com/MatrixSeven 23 | * Created by seven on 2017/1/11. 24 | */ 25 | @FunctionalInterface 26 | public interface CellStyleInterface { 27 | CellStyle create(CellStyle cellStyle); 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/PackageDataInterface.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import java.sql.ResultSet; 19 | 20 | /** 21 | * [Zhihu]https://www.zhihu.com/people/Sweets07 22 | * [Github]https://github.com/MatrixSeven 23 | * Created by seven on 2017/1/1. 24 | */ 25 | @FunctionalInterface 26 | public interface PackageDataInterface { 27 | T packageDataProcess(ResultSet res) throws Exception;} 28 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/imp/DefaultConvert.java: -------------------------------------------------------------------------------- 1 | package seven.callBack.imp; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.callBack.ConvertInterface; 20 | 21 | /** 22 | * @author Seven 23 | * FileName: DefaultConvert.java 24 | * Created by Seven on 2019/12/2 25 | **/ 26 | public class DefaultConvert implements ConvertInterface { 27 | @Override 28 | public Object convert(Object o) { 29 | return o; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implInput/LongHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implInput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | 21 | /** 22 | * @author Seven 23 | * FileName: LongHandler.java 24 | * Created by Seven on 2019/12/2 25 | **/ 26 | public class LongHandler implements InPutHandler { 27 | @Override 28 | public Long handlerConvert(String source) { 29 | return Long.parseLong(source); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implInput/DoubleHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implInput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | 21 | /** 22 | * @author Seven 23 | * FileName: DoubleHandler.java 24 | * Created by Seven on 2019/12/2 25 | **/ 26 | public class DoubleHandler implements InPutHandler { 27 | @Override 28 | public Double handlerConvert(String source) { 29 | return Double.parseDouble(source); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implInput/IntegerHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implInput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | 21 | /** 22 | * @author Seven 23 | * FileName: IntagerHandler.java 24 | * Created by Seven on 2019/12/2 25 | **/ 26 | public class IntegerHandler implements InPutHandler { 27 | @Override 28 | public Integer handlerConvert(String source) { 29 | return Integer.parseInt(source); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implInput/LocalDateHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implInput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | 21 | import java.time.LocalDate; 22 | 23 | /** 24 | * @author Seven 25 | * FileName: DateHandler.java 26 | * Created by Seven on 2019/12/2 27 | **/ 28 | public class LocalDateHandler implements InPutHandler { 29 | @Override 30 | public LocalDate handlerConvert(String source) { 31 | return LocalDate.parse(source); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/OutPutHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import javax.swing.plaf.IconUIResource; 20 | 21 | /** 22 | * @author Seven 23 | * FileName: OutPutHandler.java 24 | * Created by Seven on 2019/12/2 25 | **/ 26 | public interface OutPutHandler { 27 | 28 | default R Handler(T source) { 29 | if(source!=null){ 30 | return handlerConvert(source); 31 | } 32 | return null; 33 | 34 | } 35 | 36 | R handlerConvert(T source); 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implOutput/BaseOutPutHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implOutput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import org.apache.poi.xwpf.usermodel.BreakType; 20 | import seven.handler.OutPutHandler; 21 | 22 | /** 23 | * @author Seven 24 | * FileName: BaseOutPutHandler.java 25 | * Created by Seven on 2019/12/2 26 | **/ 27 | public class BaseOutPutHandler implements OutPutHandler { 28 | @Override 29 | public Object handlerConvert(Object source) { 30 | return source; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/ReaderObj.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.ExcelSuperInterface; 20 | 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | 25 | /** 26 | * @author Seven 27 | * FileName: WrapperObj.java 28 | * Created by Seven on 2019/11/28 29 | **/ 30 | public interface ReaderObj extends ExcelSuperInterface,T> { 31 | 32 | 33 | List Create() throws Exception; 34 | 35 | Map> CreateObjLoop() throws Exception; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/ReaderMap.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.ExcelSuperInterface; 20 | 21 | import java.util.List; 22 | import java.util.Map; 23 | 24 | /** 25 | * @author Seven 26 | * FileName: WrapperObj.java 27 | * Created by Seven on 2019/11/28 28 | **/ 29 | public interface ReaderMap extends ExcelSuperInterface { 30 | 31 | 32 | List> CreateMap() throws Exception; 33 | 34 | Map>> CreateMapLoop() throws Exception; 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implInput/LocalDateTimeHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implInput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | 21 | import java.time.LocalDateTime; 22 | import java.time.format.DateTimeFormatter; 23 | 24 | /** 25 | * @author Seven 26 | * FileName: LocalDateTimeHandler.java 27 | * Created by Seven on 2019/12/2 28 | **/ 29 | public class LocalDateTimeHandler implements InPutHandler { 30 | 31 | private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME; 32 | 33 | @Override 34 | public LocalDateTime handlerConvert(String source) { 35 | return LocalDateTime.parse(source, dateTimeFormatter); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/seven/handler/implOutput/LocalDateTimeHandler.java: -------------------------------------------------------------------------------- 1 | package seven.handler.implOutput; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.InPutHandler; 20 | import seven.handler.OutPutHandler; 21 | 22 | import java.time.LocalDateTime; 23 | import java.time.format.DateTimeFormatter; 24 | 25 | /** 26 | * @author Seven 27 | * FileName: LocalDateTimeHandler.java 28 | * Created by Seven on 2019/12/2 29 | **/ 30 | public class LocalDateTimeHandler implements OutPutHandler { 31 | 32 | private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_DATE_TIME; 33 | 34 | @Override 35 | public String handlerConvert(LocalDateTime source) { 36 | return dateTimeFormatter.format(source); 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/seven/callBack/CellStyleCallbackWrapper.java: -------------------------------------------------------------------------------- 1 | package seven.callBack; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.usermodel.Workbook; 19 | import seven.savewapper.cellStyle.CellStyle; 20 | 21 | import java.util.Map; 22 | 23 | /** 24 | * [Zhihu]https://www.zhihu.com/people/Sweets07 25 | * [Github]https://github.com/MatrixSeven 26 | * Created by seven on 2017/1/11. 27 | */ 28 | public final class CellStyleCallbackWrapper { 29 | CellStyleInterface cellStyle; 30 | String name; 31 | public CellStyleCallbackWrapper(String name, CellStyleInterface cellStyle) { 32 | this.cellStyle = cellStyle; 33 | this.name = name; 34 | } 35 | public void create(Workbook wk, Map cellStyleMap) throws Exception { 36 | cellStyleMap.put(name, cellStyle.create(CellStyle.CreateStyle(wk.createCellStyle()))); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/seven/anno/ExcelAnno.java: -------------------------------------------------------------------------------- 1 | package seven.anno; 2 | 3 | import seven.callBack.ConvertInterface; 4 | import seven.callBack.imp.DefaultConvert; 5 | 6 | import javax.swing.text.DateFormatter; 7 | import java.lang.annotation.ElementType; 8 | import java.lang.annotation.Retention; 9 | import java.lang.annotation.RetentionPolicy; 10 | import java.lang.annotation.Target; 11 | 12 | //======================================================= 13 | // .----. 14 | // _.'__ `. 15 | // .--(^)(^^)---/#\ 16 | // .' @ /###\ 17 | // : , ##### 18 | // `-..__.-' _.-\###/ 19 | // `;_: `"' 20 | // .'"""""`. 21 | // /, ya ,\\ 22 | // //狗神保佑 \\ 23 | // `-._______.-' 24 | // ___`. | .'___ 25 | // (______|______) 26 | //======================================================= 27 | 28 | /** 29 | * @author Seven 30 | */ 31 | @Target(ElementType.FIELD) 32 | @Retention(RetentionPolicy.RUNTIME) 33 | public @interface ExcelAnno { 34 | 35 | String Value() default "Null"; 36 | 37 | boolean Pass() default false; 38 | 39 | String Required() default "Null"; 40 | 41 | short Align() default 0x2; 42 | 43 | @Deprecated 44 | Class Convert() default DefaultConvert.class; 45 | 46 | String DateTimeFormatter() default "yyyy-MM-dd hh:mm:ss"; 47 | } -------------------------------------------------------------------------------- /src/main/java/seven/handler/HandlerFactory.java: -------------------------------------------------------------------------------- 1 | package seven.handler; 2 | 3 | //======================================================= 4 | // .----. 5 | // _.'__ `. 6 | // .--(^)(^^)---/!\ 7 | // .' @ /!!!\ 8 | // : , !!!! 9 | // `-..__.-' _.-\!!!/ 10 | // `;_: `"' 11 | // .'"""""`. 12 | // /, ya ,\\ 13 | // //狗神保佑\\ 14 | // `-._______.-' 15 | // ___`. | .'___ 16 | // (______|______) 17 | //======================================================= 18 | 19 | import seven.handler.implInput.*; 20 | 21 | import java.time.LocalDate; 22 | import java.time.LocalDateTime; 23 | import java.util.HashMap; 24 | import java.util.Map; 25 | 26 | /** 27 | * @author Seven 28 | * FileName: HandlerFactory.java 29 | * Created by Seven on 2019/12/2 30 | **/ 31 | @SuppressWarnings("all") 32 | public class HandlerFactory { 33 | private static final Map handler = new HashMap<>(); 34 | static { 35 | reg(); 36 | } 37 | 38 | private static void reg() { 39 | handler.put(Integer.class, new IntegerHandler()); 40 | handler.put(Double.class, new DoubleHandler()); 41 | handler.put(Long.class, new LongHandler()); 42 | handler.put(LocalDateTime.class, new LocalDateTimeHandler()); 43 | handler.put(LocalDate.class, new LocalDateHandler()); 44 | } 45 | 46 | public static InPutHandler getInPutHandler(Class clazz) { 47 | return handler.getOrDefault(clazz,it->it); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /UPDATELOG.MD: -------------------------------------------------------------------------------- 1 | ## 更新纪录 2 | 3 | #### 更新2017/01/09 4 | * 增加SetPath方法,随时切换保存路径 5 | * 增加ConvertName方法,方便自定义Excel列名称 6 | * 增加Flush方法,不在建议使用~~Save(@Deprecated)~~方法进行保存输出 7 | * 增加SetOutputStream方法,可以放入自定义流,用于支持网页Response输出 8 | * 处理一些小bug,完善异常提示信息 9 | 10 | ### 更新2017/01/06 11 | * 整合注解,导出和读取使用同一个ExcelAnno注解 12 | * 统一编码为UTF-8 13 | * 修复据库查询的导出(Object)递归越栈问题 14 | * 增加新的xxx.Class定义类型导出,操作更简单 15 | * 导出注解支持(自己使用seven.savewapper.anno.ExcelAnno类型注解) 16 | 17 | ### 更新2017/01/11 18 | * 增加AnyCol来对应FilterCol方法,只保留AnyCol类列 19 | * 增加SetCellStyle,支持方法链式设置列单元格风格 20 | 21 | ### 更新2017/01/09 22 | * 增加SetPath方法,随时切换保存路径 23 | * 增加ConvertName方法,方便自定义Excel列名称 24 | * 增加Flush方法,不在建议使用~~Save(@Deprecated)~~方法进行保存输出 25 | * 增加SetOutputStream方法,可以放入自定义流,用于支持网页Response输出 26 | * 处理一些小bug,完善异常提示信息 27 | 28 | ### 更新2017/01/06 29 | * 整合注解,导出和读取使用同一个ExcelAnno注解 30 | * 统一编码为UTF-8 31 | 32 | ### 更新2017/01/05 33 | * 修复据库查询的导出(Object)递归越栈问题 34 | * 增加新的xxx.Class定义类型导出,操作更简单 35 | * 导出注解支持(自己使用seven.savewapper.anno.ExcelAnno类型注解) 36 | 37 | ### 更新2017/01/04 38 | * 修复据库查询的导出(Map)空指针&下标越界问题 39 | * 修复在Filter数据后出现空行问题 40 | * 丢入Result参数后的操作就如同操作Map/Object一样 41 | 42 | ### 更新2017/01/01 43 | * 增加ResExportDBMap&ResExportDBObj用于支持数据库导出 44 | * 支持基于数据库查询的导出(Map),直接放入Result对象即可 45 | * 支持基于数据库查询的导出(Object),直接放入Result对象即可 46 | 47 | ### 更新2016/11/30 48 | * 增加了简单类型得写入,生成xls/xlsx 49 | * 直接JavaBean类型写入,注解命名 50 | * 支持Map key-value类型写入 51 | * 写入时支持和读取一样得过滤加工排序等写法 52 | 53 | ### 更新2016/11/29 54 | * 增加CreateMap By Key 55 | * 去除无用泛型 56 | * 增加xlsx支持 57 | 58 | ### 更新2016/11/8 59 | * 支持数据过滤和处理是转换,基于事件模式 60 | * 更新为Build模式创建实例 61 | * 增加数据过滤、数据转换和数据排序回调接口 62 | * 采用链式set方式进行 63 | 64 | ### 更新2016/06/04 65 | * 创建项目工程 66 | -------------------------------------------------------------------------------- /src/main/java/seven/ExcelSuperInterface.java: -------------------------------------------------------------------------------- 1 | package seven; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import seven.callBack.DataFilterColumnInterface; 19 | import seven.callBack.DataFilterInterface; 20 | import seven.callBack.DataFilterProcessInterface; 21 | 22 | import java.util.Comparator; 23 | import java.util.List; 24 | import java.util.function.Consumer; 25 | 26 | /** 27 | * [Zhihu]https://www.zhihu.com/people/Sweets07 28 | * [Github]https://github.com/MatrixSeven 29 | * Created by seven on 2016/12/1. 30 | */ 31 | public interface ExcelSuperInterface { 32 | 33 | /** 34 | * 对要包装的数据进行过滤,对应实体Bean\n 35 | * 如果返回false将放弃此条数据 36 | * 37 | * @param filter {@link DataFilterInterface} 38 | * @return Wrapper Wrapper 39 | */ 40 | T Filter(DataFilterInterface filter); 41 | 42 | /** 43 | * 此处传入每一行打包好的数据。对应一个实体\n 44 | * 在process方法里可对属性进行处理加工 45 | * 46 | * @param process {@link DataFilterProcessInterface} 47 | * @return Wrapper Wrapper 48 | */ 49 | T Process(DataFilterProcessInterface process); 50 | 51 | /** 52 | * 对结果的List进行排序 53 | * 54 | * @param c c 55 | * @return Wrapper Wrapper 56 | */ 57 | T Sort(Comparator c); 58 | 59 | /** 60 | * 此处过滤Excel的列数据(列名)\n 61 | * 如果加入后,将不对实体进行赋值 62 | * 63 | * @param consumer {@link DataFilterColumnInterface} 64 | * @return Wrapper Wrapper 65 | */ 66 | T FilterCol(Consumer> consumer); 67 | 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/wapperRef/sysWppers/ResExportDBMap.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.wapperRef.sysWppers; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import java.sql.ResultSet; 19 | import java.sql.ResultSetMetaData; 20 | import java.util.ArrayList; 21 | import java.util.HashMap; 22 | 23 | /** 24 | * [Zhihu]https://www.zhihu.com/people/Sweets07 25 | * [Github]https://github.com/MatrixSeven 26 | * Created by seven on 2017/1/1. 27 | */ 28 | public class ResExportDBMap extends ResExportMap { 29 | 30 | public ResExportDBMap(ResultSet resultSet, String path) { 31 | super(resultSet, path); 32 | } 33 | public ResExportDBMap(ResultSet resultSet) { 34 | super(resultSet); 35 | } 36 | 37 | public ResExportMap CreateList() throws Exception { 38 | this.list = new ArrayList<>(); 39 | HashMap stringStringHashMap; 40 | if (resultSet != null) { 41 | ResultSetMetaData res = resultSet.getMetaData(); 42 | int index = res.getColumnCount()+1 ; 43 | while (resultSet.next()) { 44 | stringStringHashMap = new HashMap<>(); 45 | for (int i = 1; i < index; i++) { 46 | stringStringHashMap.put(res.getColumnName(i), 47 | resultSet.getString(res.getColumnName(i))); 48 | } 49 | list.add(stringStringHashMap); 50 | } 51 | } 52 | return this; 53 | } 54 | 55 | @Override 56 | public void Save() throws Exception { 57 | this.CreateList(); 58 | super.Save(); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/seven/util/RegHelper.java: -------------------------------------------------------------------------------- 1 | package seven.util; 2 | 3 | import java.util.HashMap; 4 | import java.util.regex.Pattern; 5 | 6 | //======================================================= 7 | // .----. 8 | // _.'__ `. 9 | // .--(^)(^^)---/#\ 10 | // .' @ /###\ 11 | // : , ##### 12 | // `-..__.-' _.-\###/ 13 | // `;_: `"' 14 | // .'"""""`. 15 | // /, ya ,\\ 16 | // //狗神保佑 \\ 17 | // `-._______.-' 18 | // ___`. | .'___ 19 | // (______|______) 20 | //======================================================= 21 | 22 | /** 23 | * @author Seven

24 | * 2016年6月4日-下午4:07:25 25 | */ 26 | @Deprecated 27 | public class RegHelper { 28 | 29 | public static final String _REG_INT = "^\\d+$"; 30 | public static final String _REG_STRING = "Null"; 31 | public static final String _REG_FLOAT = "\\d+\\.\\d+"; 32 | public static final String _REG_DATE = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))"; 33 | public static final String _REG_EMAIL = "\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"; 34 | public static final String _REG_PHONE = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$"; 35 | private static HashMap Require_Cache; 36 | 37 | static { 38 | Require_Cache = new HashMap(); 39 | Require_Cache.put("_REG_INT", Pattern.compile(_REG_INT)); 40 | Require_Cache.put("_REG_STRING", Pattern.compile(_REG_STRING)); 41 | Require_Cache.put("_REG_FLOAT", Pattern.compile(_REG_FLOAT)); 42 | Require_Cache.put("_REG_DATE", Pattern.compile(_REG_DATE)); 43 | Require_Cache.put("_REG_EMAIL", Pattern.compile(_REG_EMAIL)); 44 | Require_Cache.put("_REG_PHONE", Pattern.compile(_REG_PHONE)); 45 | } 46 | 47 | public static boolean require(String require, String value) { 48 | if (Require_Cache.containsKey(require)) 49 | return Require_Cache.get(require).matcher(value).matches(); 50 | Require_Cache.put(require, Pattern.compile(require)); 51 | return Require_Cache.get(require).matcher(value).matches(); 52 | } 53 | 54 | } -------------------------------------------------------------------------------- /src/test/java/B.java: -------------------------------------------------------------------------------- 1 | //======================================================= 2 | // .----. 3 | // _.'__ `. 4 | // .--(^)(^^)---/!\ 5 | // .' @ /!!!\ 6 | // : , !!!! 7 | // `-..__.-' _.-\!!!/ 8 | // `;_: `"' 9 | // .'"""""`. 10 | // /, ya ,\\ 11 | // //狗神保佑\\ 12 | // `-._______.-' 13 | // ___`. | .'___ 14 | // (______|______) 15 | //======================================================= 16 | 17 | import seven.anno.ExcelAnno; 18 | 19 | /** 20 | * @author Seven 21 | * FileName: B.java 22 | * Created by Seven on 2019/12/2 23 | **/ 24 | public class B { 25 | 26 | @ExcelAnno(Value = "时间") 27 | private Integer time; 28 | @ExcelAnno(Value = "金额") 29 | private Long money; 30 | @ExcelAnno(Value = "在线人数") 31 | private Integer oneLine; 32 | @ExcelAnno(Value = "服务IP") 33 | private String ip; 34 | @ExcelAnno(Value = "地区") 35 | private String are; 36 | @ExcelAnno(Value = "创建人") 37 | private String user; 38 | @ExcelAnno(Value = "连接类型") 39 | private String type; 40 | @ExcelAnno(Value = "岁数") 41 | private Integer age; 42 | 43 | 44 | public Integer getTime() { 45 | return time; 46 | } 47 | 48 | public void setTime(Integer time) { 49 | this.time = time; 50 | } 51 | 52 | public Long getMoney() { 53 | return money; 54 | } 55 | 56 | public void setMoney(Long money) { 57 | this.money = money; 58 | } 59 | 60 | public Integer getOneLine() { 61 | return oneLine; 62 | } 63 | 64 | public void setOneLine(Integer oneLine) { 65 | this.oneLine = oneLine; 66 | } 67 | 68 | public String getIp() { 69 | return ip; 70 | } 71 | 72 | public void setIp(String ip) { 73 | this.ip = ip; 74 | } 75 | 76 | public String getAre() { 77 | return are; 78 | } 79 | 80 | public void setAre(String are) { 81 | this.are = are; 82 | } 83 | 84 | public String getUser() { 85 | return user; 86 | } 87 | 88 | public void setUser(String user) { 89 | this.user = user; 90 | } 91 | 92 | public String getType() { 93 | return type; 94 | } 95 | 96 | public void setType(String type) { 97 | this.type = type; 98 | } 99 | 100 | public Integer getAge() { 101 | return age; 102 | } 103 | 104 | public void setAge(Integer age) { 105 | this.age = age; 106 | } 107 | 108 | @Override 109 | public String toString() { 110 | return "B{" + 111 | "time=" + time + 112 | ", money=" + money + 113 | ", oneLine=" + oneLine + 114 | ", ip='" + ip + '\'' + 115 | ", are='" + are + '\'' + 116 | ", user='" + user + '\'' + 117 | ", type='" + type + '\'' + 118 | ", age=" + age + 119 | '}'; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/wapperRef/sysWppers/ResExportDBObj.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.wapperRef.sysWppers; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import seven.anno.ExcelAnno; 19 | import seven.callBack.PackageDataInterface; 20 | import seven.util.ExcelTool; 21 | 22 | import java.lang.reflect.Field; 23 | import java.sql.ResultSet; 24 | import java.util.ArrayList; 25 | 26 | /** 27 | * [Zhihu]https://www.zhihu.com/people/Sweets07 28 | * [Github]https://github.com/MatrixSeven 29 | * Created by seven on 2017/1/1. 30 | */ 31 | public class ResExportDBObj extends ResExportObj { 32 | protected PackageDataInterface dataInterface; 33 | protected Class clazz = null; 34 | 35 | public ResExportDBObj(ResultSet resultSet, String path, PackageDataInterface dataInterface) { 36 | super(resultSet, path); 37 | this.dataInterface = dataInterface; 38 | } 39 | 40 | public ResExportDBObj(ResultSet resultSet, String path, Class type) { 41 | super(resultSet, path); 42 | this.clazz = type; 43 | } 44 | 45 | public ResExportDBObj(ResultSet resultSet, Class type) { 46 | super(resultSet); 47 | this.clazz = type; 48 | } 49 | 50 | public ResExportDBObj CreateList() throws Exception { 51 | this.list = new ArrayList<>(); 52 | if (clazz != null) { 53 | Field[] fields = ExcelTool.GetFilesDeep(clazz); 54 | int len = fields.length; 55 | String[] name = new String[len]; 56 | String[] f_name = new String[len]; 57 | ExcelAnno anno = null; 58 | for (int i = 0; i < len; i++) { 59 | fields[i].setAccessible(true); 60 | if ((anno = fields[i].getAnnotation(ExcelAnno.class)) != null && !anno.Value().equals("Null")) { 61 | name[i] = anno.Value(); 62 | f_name[i] = fields[i].getName(); 63 | continue; 64 | } 65 | f_name[i] = name[i] = fields[i].getName(); 66 | } 67 | Object o = null; 68 | while (resultSet.next()) { 69 | o = clazz.newInstance(); 70 | for (int i = 0; i < len; i++) { 71 | fields[i].set(o, resultSet.getString(name[i])); 72 | } 73 | list.add(o); 74 | } 75 | return this; 76 | } 77 | while (resultSet.next()) { 78 | list.add(dataInterface.packageDataProcess(resultSet)); 79 | } 80 | return this; 81 | } 82 | 83 | @Override 84 | public void Save() throws Exception { 85 | this.CreateList(); 86 | super.Save(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/wapperRef/WrapperObj.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt.wapperRef; 2 | 3 | 4 | //======================================================= 5 | // .----. 6 | // _.'__ `. 7 | // .--(^)(^^)---/#\ 8 | // .' @ /###\ 9 | // : , ##### 10 | // `-..__.-' _.-\###/ 11 | // `;_: `"' 12 | // .'"""""`. 13 | // /, ya ,\\ 14 | // //狗神保佑 \\ 15 | // `-._______.-' 16 | // ___`. | .'___ 17 | // (______|______) 18 | //======================================================= 19 | 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import seven.callBack.DataFilterInterface; 23 | import seven.callBack.DataFilterProcessInterface; 24 | import seven.wapperInt.ReaderObj; 25 | import seven.wapperInt.Wrapper; 26 | 27 | import java.io.File; 28 | import java.util.*; 29 | import java.util.function.Consumer; 30 | 31 | /** 32 | * @author Seven

33 | * date 2016年4月12日-下午4:07:57 34 | */ 35 | @SuppressWarnings("all") 36 | public abstract class WrapperObj extends Wrapper implements ReaderObj { 37 | private static final Logger logger = LoggerFactory.getLogger(WrapperObj.class); 38 | 39 | 40 | 41 | 42 | 43 | public WrapperObj(Consumer consumer) { 44 | super(consumer); 45 | } 46 | 47 | 48 | protected boolean isNull(Map map) { 49 | boolean isN = true; 50 | for (Map.Entry s : map.entrySet()) { 51 | isN = isN && s.getValue().trim().equals(""); 52 | } 53 | return isN; 54 | } 55 | 56 | 57 | public ReaderObj init(String filePath) { 58 | this.fs = filePath; 59 | return this; 60 | } 61 | 62 | public ReaderObj init(File file) { 63 | this.fs = file.getPath(); 64 | this.file=file; 65 | return this; 66 | } 67 | 68 | public ReaderObj Sort(Comparator c) { 69 | this.c = c; 70 | return this; 71 | } 72 | 73 | public List Create() throws Exception { 74 | if (config.getIsLoopSheet()) { 75 | throw new RuntimeException("未开启LoopSheet选项,请使用CreateObjLoop"); 76 | } 77 | return refResWrapper(fs, isMap); 78 | } 79 | 80 | @Override 81 | public ReaderObj FilterCol(Consumer> consumer) { 82 | consumer.accept(filterColByKey); 83 | return this; 84 | } 85 | 86 | 87 | @Override 88 | public Map> CreateObjLoop() throws Exception { 89 | if (!config.getIsLoopSheet()) { 90 | throw new RuntimeException("未开启LoopSheet选项,请使用Create"); 91 | } 92 | return refResWrapper(fs, isMap); 93 | } 94 | 95 | 96 | @Override 97 | public ReaderObj Filter(DataFilterInterface filter) { 98 | this.filter = filter; 99 | return this; 100 | } 101 | 102 | @Override 103 | public ReaderObj Process(DataFilterProcessInterface process) { 104 | this.process = process; 105 | return this; 106 | } 107 | 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/seven/util/ExcelTool.java: -------------------------------------------------------------------------------- 1 | package seven.util; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 19 | import org.apache.poi.poifs.filesystem.POIFSFileSystem; 20 | import org.apache.poi.ss.usermodel.Workbook; 21 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 22 | 23 | import java.io.Closeable; 24 | import java.io.File; 25 | import java.lang.reflect.Field; 26 | import java.lang.reflect.Method; 27 | 28 | /** 29 | * [Zhihu]https://www.zhihu.com/people/Sweets07 30 | * [Github]https://github.com/MatrixSeven 31 | * Created by seven on 2016/11/30. 32 | */ 33 | public class ExcelTool { 34 | private ExcelTool() { 35 | } 36 | public static final Workbook newInstance(String type, boolean isSave) throws Exception { 37 | File f = new File(type); 38 | if (isSave) { 39 | if (type.equals("xls")) { 40 | return new HSSFWorkbook(); 41 | } 42 | return new XSSFWorkbook(); 43 | } 44 | if (!f.isFile()) { 45 | throw new Exception("请填写正确路径"); 46 | } 47 | type = type.substring(type.lastIndexOf(".") + 1); 48 | if (type.equals("xls")) { 49 | return new HSSFWorkbook(new POIFSFileSystem(f)); 50 | } 51 | return new XSSFWorkbook(f); 52 | } 53 | 54 | public static void Close(Closeable... close)throws Exception{ 55 | try { 56 | for(Closeable closeable:close){ 57 | if(closeable!=null){ 58 | closeable.close(); 59 | } 60 | } 61 | }catch (Exception e){ 62 | throw new Exception("关闭流出错"); 63 | } 64 | } 65 | 66 | public static Field[] GetFilesDeep(Class t) { 67 | if (!t.getSuperclass().equals(Object.class)) { 68 | Field[] fieldSu = GetFilesDeep(t.getSuperclass()); 69 | Field[] fieldSe = t.getDeclaredFields(); 70 | Field[] field = new Field[fieldSe.length + fieldSu.length]; 71 | System.arraycopy(fieldSe, 0, field, 0, fieldSe.length); 72 | System.arraycopy(fieldSu, 0, field, fieldSe.length, fieldSu.length); 73 | return field; 74 | } 75 | return t.getDeclaredFields(); 76 | } 77 | 78 | public static final Method[] GetMethodDeep(Class t) { 79 | if (!t.getSuperclass().equals(Object.class)) { 80 | Method[] MethodSu = GetMethodDeep(t.getSuperclass()); 81 | Method[] MethodSe = t.getDeclaredMethods(); 82 | Method[] Method = new Method[MethodSe.length + MethodSu.length]; 83 | System.arraycopy(MethodSe, 0, Method, 0, MethodSe.length); 84 | System.arraycopy(MethodSu, 0, Method, MethodSe.length, MethodSu.length); 85 | return Method; 86 | } 87 | return t.getDeclaredMethods(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/Wrapper.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt; 2 | 3 | import org.apache.poi.hssf.usermodel.HSSFDateUtil; 4 | import org.apache.poi.ss.usermodel.Cell; 5 | import seven.ExcelSuperInterface; 6 | import seven.callBack.DataFilterColumnInterface; 7 | import seven.callBack.DataFilterInterface; 8 | import seven.callBack.DataFilterProcessInterface; 9 | import seven.callBack.imp.DefaultDataFilter; 10 | import seven.callBack.imp.DefaultDataProFilter; 11 | import seven.config.Config; 12 | 13 | import java.io.File; 14 | import java.io.Serializable; 15 | import java.text.DecimalFormat; 16 | import java.text.SimpleDateFormat; 17 | import java.util.ArrayList; 18 | import java.util.Comparator; 19 | import java.util.Date; 20 | import java.util.List; 21 | import java.util.function.Consumer; 22 | 23 | //======================================================= 24 | // .----. 25 | // _.'__ `. 26 | // .--(^)(^^)---/#\ 27 | // .' @ /###\ 28 | // : , ##### 29 | // `-..__.-' _.-\###/ 30 | // `;_: `"' 31 | // .'"""""`. 32 | // /, ya , \\ 33 | // //狗神保佑 \\ 34 | // `-._______.-' 35 | // ___`. | .'___ 36 | // (______|______) 37 | //======================================================= 38 | 39 | /** 40 | * @author Seven

41 | * 2016年4月12日-下午4:08:08 42 | */ 43 | @SuppressWarnings("all") 44 | public abstract class Wrapper implements Serializable { 45 | protected Config config = new Config(); 46 | protected DecimalFormat df = new DecimalFormat("0"); 47 | private static final String BLANK=""; 48 | protected DataFilterInterface filter=new DefaultDataFilter(); 49 | protected DataFilterProcessInterface process=new DefaultDataProFilter(); 50 | protected List filterColByKey =new ArrayList<>(); 51 | protected List filterColByValue =new ArrayList<>(); 52 | protected Comparator c=null; 53 | protected String fs; 54 | protected File file; 55 | protected static final boolean isMap=false; 56 | 57 | protected String getCellFormatValue(Cell cell) { 58 | String cellValue; 59 | if (cell != null) { 60 | switch (cell.getCellType()) { 61 | case NUMERIC: 62 | cellValue = df.format(cell.getNumericCellValue()); 63 | break; 64 | case FORMULA: { 65 | if (HSSFDateUtil.isCellDateFormatted(cell)) { 66 | Date date = cell.getDateCellValue(); 67 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 68 | cellValue = sdf.format(date); 69 | } else { 70 | cellValue = String.valueOf(cell.getStringCellValue()); 71 | } 72 | break; 73 | } 74 | case STRING: 75 | cellValue = cell.getStringCellValue(); 76 | break; 77 | case ERROR: 78 | case BLANK: 79 | default: 80 | cellValue = BLANK; 81 | } 82 | } else { 83 | cellValue = BLANK; 84 | } 85 | return cellValue; 86 | } 87 | 88 | public Wrapper(Consumer consumer) { 89 | consumer.accept(this.config); 90 | } 91 | protected abstract T refResWrapper(String fs, boolean isMap) throws Exception; 92 | } -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/wapperRef/WrapperMap.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt.wapperRef; 2 | 3 | 4 | //======================================================= 5 | // .----. 6 | // _.'__ `. 7 | // .--(^)(^^)---/#\ 8 | // .' @ /###\ 9 | // : , ##### 10 | // `-..__.-' _.-\###/ 11 | // `;_: `"' 12 | // .'"""""`. 13 | // /, ya ,\\ 14 | // //狗神保佑 \\ 15 | // `-._______.-' 16 | // ___`. | .'___ 17 | // (______|______) 18 | //======================================================= 19 | 20 | import org.slf4j.Logger; 21 | import org.slf4j.LoggerFactory; 22 | import seven.callBack.DataFilterInterface; 23 | import seven.callBack.DataFilterProcessInterface; 24 | import seven.wapperInt.ReaderMap; 25 | import seven.wapperInt.Wrapper; 26 | 27 | import java.io.File; 28 | import java.util.Comparator; 29 | import java.util.List; 30 | import java.util.Map; 31 | import java.util.function.Consumer; 32 | 33 | /** 34 | * @author Seven

35 | * date 2016年4月12日-下午4:07:57 36 | */ 37 | @SuppressWarnings("all") 38 | public abstract class WrapperMap extends Wrapper implements ReaderMap { 39 | private static final Logger logger = LoggerFactory.getLogger(WrapperMap.class); 40 | 41 | public WrapperMap(Consumer consumer) { 42 | super(consumer); 43 | } 44 | 45 | 46 | protected boolean isNull(Map map) { 47 | boolean isN = true; 48 | for (Map.Entry s : map.entrySet()) { 49 | isN = isN && s.getValue().trim().equals(""); 50 | } 51 | return isN; 52 | } 53 | 54 | 55 | public Wrapper init(String filePath) { 56 | this.fs = filePath; 57 | return this; 58 | } 59 | 60 | public Wrapper init(File file) { 61 | this.fs = file.getPath(); 62 | this.file = file; 63 | return this; 64 | } 65 | 66 | public ReaderMap Sort(Comparator c) { 67 | this.c = c; 68 | return this; 69 | } 70 | 71 | public List Create() throws Exception { 72 | if (config.getIsLoopSheet()) { 73 | throw new RuntimeException("未开启LoopSheet选项,请使用CreateObjLoop"); 74 | } 75 | return refResWrapper(fs, isMap); 76 | } 77 | 78 | @Override 79 | public ReaderMap FilterCol(Consumer> consumer) { 80 | consumer.accept(filterColByKey); 81 | return this; 82 | } 83 | 84 | @Override 85 | public List> CreateMap() throws Exception { 86 | if (config.getIsLoopSheet()) { 87 | throw new RuntimeException("开启LoopSheet选项,请使用CreateMapLoop"); 88 | } 89 | return refResWrapper(fs, isMap); 90 | } 91 | 92 | @Override 93 | public Map>> CreateMapLoop() throws Exception { 94 | if (!config.getIsLoopSheet()) { 95 | throw new RuntimeException("未开启LoopSheet选项,请使用CreateMap"); 96 | } 97 | return refResWrapper(fs, isMap); 98 | } 99 | 100 | 101 | @Override 102 | public ReaderMap Filter(DataFilterInterface filter) { 103 | this.filter = filter; 104 | return this; 105 | } 106 | 107 | @Override 108 | public ReaderMap Process(DataFilterProcessInterface process) { 109 | this.process = process; 110 | return this; 111 | } 112 | 113 | 114 | } 115 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/SaveExcel.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.formula.functions.T; 19 | import seven.ExcelSuperInterface; 20 | import seven.callBack.CellStyleInterface; 21 | import seven.callBack.DataFilterColumnInterface; 22 | import seven.callBack.DataFilterInterface; 23 | import seven.callBack.DataFilterProcessInterface; 24 | 25 | import java.io.OutputStream; 26 | import java.util.Comparator; 27 | import java.util.HashMap; 28 | import java.util.List; 29 | import java.util.function.Consumer; 30 | 31 | /** 32 | * [Zhihu]https://www.zhihu.com/people/Sweets07 33 | * [Github]https://github.com/MatrixSeven 34 | * Created by seven on 2016/11/30. 35 | */ 36 | public interface SaveExcel { 37 | 38 | /** 39 | * 请使用Flush 40 | * 41 | * @throws Exception 42 | */ 43 | @Deprecated 44 | void Save() throws Exception; 45 | 46 | /** 47 | * 对要包装的数据进行过滤,对应实体Bean\n 48 | * 如果返回false将放弃此条数据 49 | * 50 | * @param filter {@link DataFilterInterface} 51 | * @return 52 | */ 53 | SaveExcel Filter(DataFilterInterface filter); 54 | 55 | /** 56 | * 此处传入每一行打包好的数据。对应一个实体\n 57 | * 在process方法里可对属性进行处理加工 58 | * 59 | * @param process {@link DataFilterProcessInterface} 60 | * @return 61 | */ 62 | SaveExcel Process(DataFilterProcessInterface process); 63 | 64 | 65 | /** 66 | * 对结果的List进行排序 67 | * 68 | * @param c 69 | * @return 70 | */ 71 | SaveExcel Sort(Comparator c); 72 | 73 | /** 74 | * 此处过滤Excel的列数据(列名)\n 75 | * 如果加入后,只保留对应数据 76 | * 77 | * @param consumer {@link DataFilterColumnInterface} 78 | */ 79 | SaveExcel FilterCol(Consumer> consumer); 80 | 81 | /** 82 | * 此处过滤Excel的列数据(列名)\n 83 | * 如果加入后,删除这些列 84 | * 85 | * @param consumer {@link DataFilterColumnInterface} 86 | */ 87 | SaveExcel AnyCol(Consumer> consumer); 88 | 89 | /** 90 | * 网页输出流 91 | * 92 | * @param stream 93 | * @return 94 | */ 95 | SaveExcel SetOutputStream(OutputStream stream) throws Exception; 96 | 97 | /** 98 | * @throws Exception 99 | */ 100 | void Flush() throws Exception; 101 | 102 | /** 103 | * 设置保存路径 104 | * 105 | * @param path 106 | */ 107 | SaveExcel SetPath(String path); 108 | 109 | /** 110 | * 转换字段名称 111 | * 112 | * @param title 113 | * @param newTitle 114 | * @return 115 | */ 116 | SaveExcel ConvertName(String title, String newTitle); 117 | 118 | /** 119 | * 转换字段 120 | * 121 | * @param titleMapping 122 | * @return 123 | */ 124 | SaveExcel ConvertName(HashMap titleMapping); 125 | 126 | /** 127 | * 转换字段 128 | * 129 | * @param titleMapping 130 | * @return 131 | */ 132 | SaveExcel ConvertName(HashMap titleMapping, Boolean isInit); 133 | 134 | /** 135 | * 设置风格.必须保证wk不能为null。 136 | * 137 | * @param name 138 | * @param cellStyle 139 | * @return 140 | */ 141 | SaveExcel SetCellStyle(String name, CellStyleInterface cellStyle); 142 | } 143 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 3 | 4.0.0 4 | com.github.matrixseven 5 | ExcelReads 6 | jar 7 | 1.0.4 8 | ExcelReads 9 | A ExcelReads Utils By Seven 10 | https://github.com/MatrixSeven/ExcelReads 11 | 12 | 13 | The Apache Software License, Version 2.0 14 | http://www.apache.org/licenses/LICENSE-2.0.txt 15 | repo 16 | 17 | 18 | 19 | https://github.com/MatrixSeven/ExcelReads 20 | https://github.com/MatrixSeven/ExcelReads.git 21 | https://github.com/MatrixSeven/ExcelReads 22 | 23 | 24 | 25 | Seven 26 | hacker.kill07@gmail.com 27 | https://matrixseven.github.io 28 | 29 | 30 | 31 | 32 | ossrh 33 | https://oss.sonatype.org/content/repositories/snapshots 34 | 35 | 36 | ossrh 37 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 38 | 39 | 40 | 41 | 42 | 43 | 44 | org.apache.poi 45 | poi 46 | 4.0.1 47 | 48 | 49 | org.apache.poi 50 | poi-ooxml 51 | 4.0.1 52 | 53 | 54 | junit 55 | junit 56 | 4.12 57 | test 58 | 59 | 60 | org.slf4j 61 | slf4j-api 62 | 1.7.25 63 | 64 | 65 | 66 | 67 | 68 | maven-compiler-plugin 69 | 3.1 70 | 71 | 1.8 72 | 1.8 73 | 74 | 75 | 76 | org.apache.maven.plugins 77 | maven-source-plugin 78 | 2.2.1 79 | 80 | 81 | attach-sources 82 | 83 | jar-no-fork 84 | 85 | 86 | 87 | 88 | 89 | org.apache.maven.plugins 90 | maven-javadoc-plugin 91 | 2.9.1 92 | 93 | 94 | attach-javadocs 95 | package 96 | 97 | jar 98 | 99 | 100 | -Xdoclint:none 101 | 102 | 103 | 104 | 105 | 106 | org.apache.maven.plugins 107 | maven-gpg-plugin 108 | 1.5 109 | 110 | 111 | sign-artifacts 112 | verify 113 | 114 | sign 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/wapperRef/sysWppers/ResExportMap.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.wapperRef.sysWppers; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.usermodel.*; 19 | import seven.savewapper.wapperRef.SaveExcelObject; 20 | import seven.util.ExcelTool; 21 | 22 | import java.io.OutputStream; 23 | import java.sql.ResultSet; 24 | import java.util.*; 25 | 26 | /** 27 | * [Zhihu]https://www.zhihu.com/people/Sweets07 28 | * [Github]https://github.com/MatrixSeven 29 | * Created by seven on 2016/11/30. 30 | */ 31 | @SuppressWarnings("all") 32 | public class ResExportMap extends SaveExcelObject { 33 | 34 | public ResExportMap(List list) { 35 | super(list); 36 | } 37 | 38 | public ResExportMap(List list, String path) { 39 | super(list, path); 40 | } 41 | 42 | public ResExportMap(ResultSet resultSet, String path) { 43 | super(resultSet, path); 44 | } 45 | 46 | public ResExportMap(ResultSet resultSet) { 47 | super(resultSet); 48 | } 49 | 50 | 51 | @Override 52 | @Deprecated 53 | public void Save() throws Exception { 54 | OutputStream out = createStream(); 55 | createWK(); 56 | tryCreateCellStyle(); 57 | checkData(); 58 | if (c != null) { 59 | list.sort(c); 60 | } 61 | Sheet sheet = wk.createSheet("sheet1"); 62 | sheet.setDefaultColumnWidth((short) 15); 63 | // 生成一个样式 64 | CellStyle style = wk.createCellStyle(); 65 | // 设置这些样式 66 | 67 | style.setAlignment(HorizontalAlignment.CENTER); 68 | Map m = list.get(0); 69 | Set setTitle = m.keySet(); 70 | Iterator it = setTitle.iterator(); 71 | String t; 72 | String[] title; 73 | List l = new ArrayList(); 74 | 75 | if (!anyColByKey.isEmpty()) { 76 | for (Map o : list) { 77 | if (!filter.test(o)) { 78 | HashSet strings = new HashSet<>(setTitle); 79 | strings.removeAll(setTitle); 80 | if (!strings.isEmpty()) { 81 | throw new Exception("字段名无效"); 82 | } 83 | } 84 | } 85 | title = anyColByKey.toArray(new String[anyColByKey.size()]); 86 | } else { 87 | while (it.hasNext()) { 88 | t = it.next(); 89 | if (!filterColByKey.contains(t)) { 90 | l.add(t); 91 | } 92 | } 93 | title = l.toArray(new String[l.size()]); 94 | } 95 | 96 | Row row = sheet.createRow(0); 97 | 98 | initTitle(title, row, style); 99 | 100 | int index = 0; 101 | for ( 102 | Map o : list) { 103 | if (!filter.test(o)) { 104 | continue; 105 | } 106 | row = sheet.createRow(++index); 107 | process.accept(o);//加工每一行 108 | for (int i = 0; i < title.length; i++) { 109 | Cell cell = row.createCell(i); 110 | cell.setCellStyle(style); 111 | if (cellStyle.containsKey(title[i])) { 112 | cell.setCellStyle(cellStyle.get(title[i]).getRealyStyle()); 113 | } 114 | cell.setCellValue(o.get(title[i])); 115 | } 116 | } 117 | try { 118 | wk.write(out); 119 | out.flush(); 120 | 121 | } finally { 122 | ExcelTool.Close(wk, out); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/cellStyle/CellStyle.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.cellStyle; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.usermodel.*; 19 | 20 | /** 21 | * [Zhihu]https://www.zhihu.com/people/Sweets07 22 | * [Github]https://github.com/MatrixSeven 23 | * Created by seven on 2017/1/11. 24 | */ 25 | public class CellStyle { 26 | 27 | private CellStyle(org.apache.poi.ss.usermodel.CellStyle cellStyle) { 28 | this.cellStyle = cellStyle; 29 | } 30 | 31 | public CellStyle setDataFormat(short fmt) { 32 | cellStyle.setDataFormat(fmt); 33 | return this; 34 | } 35 | 36 | public CellStyle setFont(Font font) { 37 | cellStyle.setFont(font); 38 | return this; 39 | } 40 | 41 | public CellStyle setHidden(boolean hidden) { 42 | cellStyle.setHidden(hidden); 43 | return this; 44 | } 45 | 46 | public CellStyle setLocked(boolean locked) { 47 | cellStyle.setLocked(locked); 48 | return this; 49 | } 50 | 51 | public CellStyle setAlignment(HorizontalAlignment align) { 52 | cellStyle.setAlignment(align); 53 | return this; 54 | } 55 | 56 | public CellStyle setWrapText(boolean wrapped) { 57 | cellStyle.setWrapText(wrapped); 58 | return this; 59 | } 60 | 61 | public CellStyle setVerticalAlignment(VerticalAlignment align) { 62 | cellStyle.setVerticalAlignment(align); 63 | return this; 64 | } 65 | 66 | public CellStyle setRotation(short rotation) { 67 | cellStyle.setRotation(rotation); 68 | return this; 69 | } 70 | 71 | public CellStyle setIndention(short indent) { 72 | cellStyle.setIndention(indent); 73 | return this; 74 | } 75 | 76 | public CellStyle setBorderLeft(BorderStyle border) { 77 | cellStyle.setBorderLeft(border); 78 | return this; 79 | } 80 | 81 | public CellStyle setBorderRight(BorderStyle border) { 82 | cellStyle.setBorderRight(border); 83 | return this; 84 | } 85 | 86 | public CellStyle setBorderTop(BorderStyle border) { 87 | cellStyle.setBorderTop(border); 88 | return this; 89 | } 90 | 91 | public CellStyle setBorderBottom(BorderStyle border) { 92 | cellStyle.setBorderBottom(border); 93 | return this; 94 | } 95 | 96 | public CellStyle setLeftBorderColor(short color) { 97 | cellStyle.setLeftBorderColor(color); 98 | return this; 99 | } 100 | 101 | public CellStyle setRightBorderColor(short color) { 102 | cellStyle.setRightBorderColor(color); 103 | return this; 104 | } 105 | 106 | public CellStyle setTopBorderColor(short color) { 107 | cellStyle.setTopBorderColor(color); 108 | return this; 109 | } 110 | 111 | public CellStyle setBottomBorderColor(short color) { 112 | cellStyle.setBottomBorderColor(color); 113 | return this; 114 | } 115 | 116 | public CellStyle setFillPattern(FillPatternType fp) { 117 | cellStyle.setFillPattern(fp); 118 | return this; 119 | } 120 | 121 | public CellStyle setFillBackgroundColor(short bg) { 122 | cellStyle.setFillBackgroundColor(bg); 123 | return this; 124 | } 125 | 126 | public CellStyle setFillForegroundColor(short bg) { 127 | cellStyle.setFillForegroundColor(bg); 128 | return this; 129 | } 130 | 131 | public CellStyle cloneStyleFrom(org.apache.poi.ss.usermodel.CellStyle source) { 132 | cellStyle.cloneStyleFrom(source); 133 | return this; 134 | } 135 | 136 | public CellStyle setShrinkToFit(boolean shrinkToFit) { 137 | cellStyle.setShrinkToFit(shrinkToFit); 138 | return this; 139 | } 140 | 141 | public org.apache.poi.ss.usermodel.CellStyle getRealyStyle() { 142 | return this.cellStyle; 143 | } 144 | 145 | private org.apache.poi.ss.usermodel.CellStyle cellStyle; 146 | public static final CellStyle CreateStyle(org.apache.poi.ss.usermodel.CellStyle cellStyle ) { 147 | return new CellStyle(cellStyle); 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/wapperRef/sysWppers/ResExportObj.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.wapperRef.sysWppers; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑\\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.formula.functions.T; 19 | import org.apache.poi.ss.usermodel.*; 20 | import seven.anno.ExcelAnno; 21 | import seven.savewapper.wapperRef.SaveExcelObject; 22 | import seven.util.ExcelTool; 23 | 24 | import java.io.OutputStream; 25 | import java.lang.reflect.Field; 26 | import java.sql.ResultSet; 27 | import java.util.List; 28 | 29 | /** 30 | * [Zhihu]https://www.zhihu.com/people/Sweets07 31 | * [Github]https://github.com/MatrixSeven 32 | * Created by seven on 2016/11/30. 33 | */ 34 | public class ResExportObj extends SaveExcelObject { 35 | 36 | public ResExportObj(List list, String path) { 37 | super(list, path); 38 | } 39 | public ResExportObj(ResultSet resultSet, String path) { 40 | super(resultSet, path); 41 | } 42 | public ResExportObj(List list){ 43 | super(list); 44 | }; 45 | public ResExportObj(ResultSet resultSet) { 46 | super(resultSet); 47 | } 48 | 49 | @Override 50 | @Deprecated 51 | public void Save() throws Exception { 52 | OutputStream out =createStream(); 53 | createWK(); 54 | tryCreateCellStyle(); 55 | checkData(); 56 | Class clazz = list.get(0).getClass(); 57 | Field[] fields = ExcelTool.GetFilesDeep(clazz); 58 | String[] title = new String[fields.length]; 59 | short[] align = new short[fields.length]; 60 | ExcelAnno ea = null; 61 | if(anyColByKey.isEmpty()) { 62 | for (int i = 0; i < fields.length; i++) { 63 | fields[i].setAccessible(true); 64 | //过滤列 65 | if (filterColByKey.contains(fields[i].getName())) { 66 | continue; 67 | } 68 | 69 | ea = fields[i].getAnnotation(ExcelAnno.class); 70 | if (ea != null) { 71 | if(ea.Pass()) { 72 | continue; 73 | }} 74 | title[i] = fields[i].getName(); 75 | align[i] = 0x2; 76 | if (ea != null) { 77 | if(ea.Align()!=0x2){ 78 | align[i] = ea.Align(); 79 | } 80 | if (!ea.Value().equals("Null")) { 81 | title[i] = ea.Value(); 82 | } 83 | } 84 | } 85 | }else { 86 | for (int i = 0; i < fields.length; i++) { 87 | fields[i].setAccessible(true); 88 | if(!anyColByKey.contains(fields[i].getName())){ 89 | throw new Exception("字段名无效"); 90 | } 91 | } 92 | title = anyColByKey.toArray(new String[anyColByKey.size()]); 93 | } 94 | 95 | 96 | if (c != null) { 97 | list.sort(c); 98 | } 99 | Sheet sheet = wk.createSheet("sheet1"); 100 | sheet.setDefaultColumnWidth((short) 15); 101 | CellStyle style = wk.createCellStyle(); 102 | style.setAlignment(HorizontalAlignment.CENTER); 103 | Row row = sheet.createRow(0); 104 | initTitle(title,row,style); 105 | int index = 0; 106 | Object object=null; 107 | String fn; 108 | for (T o : list) { 109 | //过滤行 110 | if (!filter.test(o)) { 111 | continue; 112 | } 113 | process.accept(o);//加工每一行 114 | row = sheet.createRow(++index); 115 | for (int i = 0; i < title.length; i++) { 116 | Cell cell = row.createCell(i); 117 | cell.setCellStyle(style); 118 | object=fields[i].get(o); 119 | if(cellStyle.containsKey(title[i])){ 120 | cell.setCellStyle(cellStyle.get(title[i]).getRealyStyle()); 121 | } 122 | cell.setCellValue(object==null?"":object.toString()); 123 | 124 | } 125 | } 126 | 127 | try { 128 | wk.write(out); 129 | out.flush(); 130 | } finally { 131 | ExcelTool.Close(wk,out); 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ExcelReads(简单Excel通用读写器) 2 | 3 | ![Apache License, Version 2.0, January 2004](https://img.shields.io/github/license/apache/maven.svg?label=License) 4 | ![Jenkins Status](https://img.shields.io/badge/build-passing-green) 5 | ![last_release](https://img.shields.io/badge/release-1.0.4-green) 6 | ![language](https://img.shields.io/badge/language-java-orange.svg) 7 | ## ExcelReads是什么? 8 | * 这是一个通用的简单的Excel读取器 9 | * 支持自定义JavaBean实体读取和HashMap自动读取 10 | * 支持自定义扩展 11 | * 支持自定义Sheet范围,数据开始行数 12 | * 支持数据库查询直接导出Excel(Map/Object) 13 | * 支持正则过滤数据格式 14 | * JavaBean实体支持使用注解添加正则规则校验,HashMap支持数组规则校验 15 | * 依赖POI,使用Maven构建 16 | 17 | 在项目的pom文件增加下面内容,即可食用! Enjoy it!!! 18 | ```xml 19 | 20 | com.github.matrixseven 21 | ExcelReads 22 | 1.0.4 23 | 24 | 25 | 26 | 27 | ``` 28 | 29 | ## [更新日志详见:UpdateLogs.md](UPDATELOG.MD) 30 | ### 最近三次更新: 31 | 32 | 33 | #### 更新2019/12/2  34 | * 替换导出方式 35 | * 增加 Create/CreateLoop[Map|Obj] 36 | * 更新顶层接口 37 | 38 | #### 更新2019/4/26 (诈尸更新) 39 | * 更加完善的类型推导,书写更方便(Great!!!) 40 | * 修复增加过滤列无法读取数据bug 41 | * 替换一些接口为Java8内置接口 42 | * 更流畅优雅的调用方法 43 | * 标注一些不建议使用的类/方法/属性 44 | 45 | #### 更新2017/01/11 46 | * 增加AnyCol来对应FilterCol方法,只保留AnyCol类列 47 | * 增加SetCellStyle,突破CellStyle绑定wk约束,链式设置列单元格风格(非常狗血) 48 | 49 | 50 | ### 其他 51 | * 自定义读取支持出简单的规范化数据格式,即典型的表头格式 52 | * 可以继承 WapperMap 和 WapperObj进行扩展 53 | * 直接使用ExcelFactory.getBeans进行获取,WapperObj则自己添加泛型 54 | * 注解Value对应列标题,Required对应正则,可自己写正则表达式或者直接使用RegHelper 55 | * 实体bean数据要比hashMap慢,7w条数据慢800ms,加入正则减慢速度(测试中加入了正则) 56 | 57 | ## 使用方法说明 58 | 1. 本程序只能读取简单格式的xls/xlsx文件,文件布局如下(标准的行列结构):
59 | 60 | | 标题1 | 标题2 | 标题3 | 61 | |:-----:|:-----:|:-----:| 62 | |foo | foo | foo | 63 | |bar | bar | bar | 64 | |baz | baz | baz | 65 | 66 | ### 读取Excel 67 | 68 | * 喜大若奔(。・・)ノ Filter/Sort等lambda操作不用在声明类型(~~还是要写一个泛型~~) 69 | ```java 70 | //CreateMapLoop 多sheet|isLoopSheet 71 | Map> maps = ExcelFactory.getMaps(filePath, it -> it.vocSize(1999) 72 | .title(2) 73 | .content(3) 74 | .isLoopSheet(true)) 75 | .Filter(it -> it.get("在线人数").equals("43")) 76 | .CreateMapLoop(); 77 | //CreateMap 单个 78 | List> maps2 = ExcelFactory.getMaps(filePath, it -> it.vocSize(1999) 79 | .title(2) 80 | .content(3)) 81 | .Filter(it -> it.get("在线人数").equals("43")) 82 | .CreateMap(); 83 | //Create Obj 84 | List create = ExcelFactory.getBeans(B.class, filePath, it -> it.title(2) 85 | .content(3)).Create(); 86 | //CreateObjLoop 87 | String filePath2 = System.getProperty("user.dir").concat("/seven.xlsx"); 88 | Map> stringListMap = ExcelFactory.getBeans(A.class, filePath2, 89 | it -> it.withConvert("姓名", ConvertTest.class) 90 | .isLoopSheet(true) 91 | .withConvert("姓名", f -> f.toString().concat("111111111"))) 92 | .Process(a -> a.setA(a.getA() + "fuck")) 93 | .CreateObjLoop(); 94 | ``` 95 | ## 数据库导出自定义Bean类型写法(xxx.Class类型) 96 | ```java 97 | Result data=UNPOOLED_DATA_SOURCE.getConnection().prepareStatement("select * FROM users_info limit 1000").executeQuery() 98 | ExcelFactory.saveExcel(data,filePath,AS.class) 99 | .Filter(o->o.getA().length() > 3) 100 | .Flush(); 101 | 102 | //ConvertName 转行列名 103 | ExcelFactory.saveExcel(ps.executeQuery()).SetPath("seven.xlsx") 104 | .Process(it->it.put("address",it.get("address").concat("seven"))) 105 | .SetCellStyle("A", cellStyle -> cellStyle 106 | .setFillPattern(FillPatternType.DIAMONDS) 107 | .setAlignment(HorizontalAlignment.RIGHT) 108 | .setFillForegroundColor(HSSFColor.WHITE.index) 109 | .setBottomBorderColor(HSSFColor.RED.index) 110 | .setFillBackgroundColor(HSSFColor.GOLD.index) 111 | .setRightBorderColor(HSSFColor.INDIGO.index)) 112 | .ConvertName("address","地址") 113 | .ConvertName("name","姓名") 114 | .Flush(); 115 | ``` 116 | 117 | ## 效果 118 | ![ExcelReads](效果_.png) 119 | ## 实体类截图 120 | ![ExcelReads](实体类.png) 121 | ## 继承关系 122 | ![ExcelReads](关系.png) 123 | ## 引用关系 124 | ![ExcelReads](引用.png) 125 | ## 写入效果 126 | ![ExcelReads](write.png) 127 | 128 | ## 129 | * 邮件(hacker.kill07@gmail.com) 130 | * QQ: 985390927 131 | * weibo: [@Alden_情绪控](http://weibo.com/Sweets07) 132 | * Blog: [http://blog.52python.cn](http://blog.52python.cn) 133 | 134 | ## Acknowledgement 135 | !特别感谢 [JetBrains](https://www.jetbrains.com/?from=matrixSeven) 为开源项目提供免费的 [IntelliJ IDEA](https://www.jetbrains.com/idea/?from=matrixSeven) 等 IDE 的授权 136 | [](https://www.jetbrains.com/?from=matrixSeven) 137 | -------------------------------------------------------------------------------- /src/test/java/Demo.java: -------------------------------------------------------------------------------- 1 | //======================================================= 2 | // .----. 3 | // _.'__ `. 4 | // .--(^)(^^)---/!\ 5 | // .' @ /!!!\ 6 | // : , !!!! 7 | // `-..__.-' _.-\!!!/ 8 | // `;_: `"' 9 | // .'"""""`. 10 | // /, ya ,\\ 11 | // //狗神保佑\\ 12 | // `-._______.-' 13 | // ___`. | .'___ 14 | // (______|______) 15 | //======================================================= 16 | 17 | import org.apache.poi.ss.usermodel.FillPatternType; 18 | import org.apache.poi.ss.usermodel.HorizontalAlignment; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.junit.runners.BlockJUnit4ClassRunner; 22 | import seven.ExcelFactory; 23 | import seven.anno.ExcelAnno; 24 | 25 | 26 | import java.time.LocalDateTime; 27 | import java.util.*; 28 | import java.util.List; 29 | 30 | /** 31 | * [Zhihu]https://www.zhihu.com/people/Sweets07 32 | * [Github]https://github.com/MatrixSeven 33 | * Created by seven on 2016/11/29. 34 | */ 35 | @RunWith(BlockJUnit4ClassRunner.class) 36 | public class Demo { 37 | @Test 38 | public void Test_01() throws Exception { 39 | 40 | String filePath = System.getProperty("user.dir").concat("/测试.xlsx"); 41 | 42 | //CreateMapLoop 43 | Map>> maps = ExcelFactory.getMaps(filePath, it -> it.vocSize(1999) 44 | .title(2) 45 | .content(3) 46 | .isLoopSheet(true)) 47 | .Filter(it -> it.get("在线人数").equals("43")) 48 | .CreateMapLoop(); 49 | System.out.println(maps); 50 | //CreateMap 51 | List> maps2 = ExcelFactory.getMaps(filePath, it -> it.vocSize(1999) 52 | .title(2) 53 | .content(3)) 54 | .Filter(it -> it.get("在线人数").equals("43")) 55 | .CreateMap(); 56 | //Create Obj 57 | List create = ExcelFactory.getBeans(B.class, filePath, it -> it.title(2) 58 | .content(3)).Create(); 59 | System.out.println(create); 60 | // CreateObjLoop 61 | Map> stringListMap = ExcelFactory.getBeans(B.class, filePath, 62 | it -> it.isLoopSheet(true) 63 | .title(2) 64 | .content(3)) 65 | // .withConvert("name", f -> f.concat("111111111"))) 66 | .Process(a -> a.setAre(a.getAre().concat("|fuck"))) 67 | .CreateObjLoop(); 68 | System.out.println(stringListMap); 69 | 70 | 71 | } 72 | 73 | @Test 74 | public void Test_02() throws Exception { 75 | List aa = new ArrayList<>(); 76 | aa.add(new A("小明", 15, LocalDateTime.now())); 77 | aa.add(new A("小绿", 13, LocalDateTime.now())); 78 | aa.add(new A("唐山", 18, LocalDateTime.now())); 79 | aa.add(new A("狗东", 15, LocalDateTime.now())); 80 | aa.add(new A("百毒", 12, LocalDateTime.now())); 81 | ExcelFactory.saveExcel(aa, System.getProperty("user.dir").concat("/seven.xlsx")) 82 | //.Filter(a -> a.getA().equals("唐山")) 83 | //.Process(a -> a.setA(a.getA().concat("_seven"))) 84 | .Sort(Comparator.comparing(A::getA)) 85 | .Flush(); 86 | 87 | 88 | List> m = new ArrayList<>(); 89 | Map mm = new HashMap<>(); 90 | mm.put("姓名", "w"); 91 | mm.put("年龄", "1"); 92 | mm.put("性别", "w3"); 93 | Map mmm = new HashMap<>(); 94 | mmm.put("姓名", "23"); 95 | mmm.put("年龄", "w3asf2"); 96 | mmm.put("性别", "w二3"); 97 | m.add(mm); 98 | m.add(mmm); 99 | ExcelFactory.saveExcel(m, System.getProperty("user.dir").concat("/SaveMap_.xlsx")) 100 | .SetCellStyle("A", cellStyle -> cellStyle.setFillPattern(FillPatternType.DIAMONDS) 101 | .setAlignment(HorizontalAlignment.RIGHT)) 102 | .Flush(); 103 | 104 | } 105 | 106 | @Test 107 | public void Test_03() throws Exception { 108 | Map>> maps = ExcelFactory.getMaps("/home/seven/Desktop/fqlde.xlsx", it -> it.title(0) 109 | .content(1) 110 | .isLoopSheet(true)) 111 | .CreateMapLoop(); 112 | System.out.println(maps); 113 | 114 | 115 | } 116 | } 117 | 118 | class A { 119 | @ExcelAnno(Value = "姓名") 120 | private String A; 121 | @ExcelAnno(Value = "年龄", Convert = ConvertTest.class) 122 | private Integer B; 123 | 124 | @ExcelAnno(Value = "日期") 125 | private LocalDateTime localDateTime; 126 | 127 | public A() { 128 | } 129 | 130 | public A(String a, Integer b, LocalDateTime localDateTime) { 131 | A = a; 132 | B = b; 133 | this.localDateTime = localDateTime; 134 | } 135 | 136 | public String getA() { 137 | return A; 138 | } 139 | 140 | public void setA(String a) { 141 | A = a; 142 | } 143 | 144 | public Integer getB() { 145 | return B; 146 | } 147 | 148 | public void setB(Integer b) { 149 | B = b; 150 | } 151 | 152 | @Override 153 | public String toString() { 154 | return "A{" + "A='" + A + '\'' + ", B='" + B + '\'' + '}'; 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/main/java/seven/config/Config.java: -------------------------------------------------------------------------------- 1 | package seven.config; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import seven.callBack.ConvertInterface; 6 | 7 | import java.util.Arrays; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | import java.util.Objects; 11 | 12 | public class Config { 13 | private static final Logger logger = LoggerFactory.getLogger(Config.class); 14 | 15 | private Integer titleRow = 0; 16 | private Integer contentRowStart = 1; 17 | private Integer contentRowEnd = null; 18 | private Boolean isLoopSheet = false; 19 | private Boolean errorLog = false; 20 | private Integer vocSize = 128; 21 | @Deprecated 22 | private String[] require = null; 23 | private Integer startSheet = 0; 24 | private Integer endSheet = null; 25 | private Integer sheetIndex = -1; 26 | private String sheetName = null; 27 | private Map>> convertMap = new HashMap<>(); 29 | private Map> convertMapImpl = new HashMap<>(); 30 | 31 | public Config() { 32 | } 33 | 34 | private boolean args(Object... params) { 35 | return Arrays.stream(params).anyMatch(Objects::isNull); 36 | } 37 | 38 | public void check() throws RuntimeException { 39 | if (args(titleRow, contentRowStart)) { 40 | logger.error("config[titleRow,contentRowStart] is null, the config {}", this); 41 | throw new RuntimeException("onfig[titleRow,contentRowStart] is null"); 42 | } else { 43 | logger.info("config[titleRow,contentRowStart] is null, the config {}", this); 44 | } 45 | 46 | } 47 | 48 | @Deprecated 49 | public String[] getRequire() { 50 | return require; 51 | } 52 | 53 | /** 54 | * Map数据个校验数组 55 | *

56 | * 支持正则表达式 57 | * @param require require 58 | * @see seven.util.RegHelper 59 | */ 60 | @Deprecated 61 | public void setRequire(String[] require) { 62 | this.require = require; 63 | } 64 | 65 | public Integer getVocSize() { 66 | return vocSize; 67 | } 68 | 69 | /** 70 | * Excel数据容器
71 | * 当数据大于5w时,最好初始化为大于或者等于当前excel行数 最好设置大于或者 72 | * @return Config Config 73 | * @param vocSize vocSize 74 | */ 75 | public Config vocSize(Integer vocSize) { 76 | this.vocSize = vocSize; 77 | return this; 78 | } 79 | 80 | public Boolean getErrorLog() { 81 | return errorLog; 82 | } 83 | 84 | public Config setErrorLog(Boolean errorLog) { 85 | this.errorLog = errorLog; 86 | return this; 87 | } 88 | 89 | /** 90 | * 91 | * @param name name 92 | * @param clazz clazz 93 | * @return Config Config 94 | */ 95 | @Deprecated 96 | public Config withConvert(String name, Class> clazz) { 97 | this.convertMap.put(name, clazz); 98 | return this; 99 | } 100 | 101 | /** 102 | * @param name name 103 | * @param convert convert 104 | * @return Config 105 | */ 106 | @Deprecated 107 | public Config withConvert(String name, ConvertInterface convert) { 108 | this.convertMapImpl.put(name, convert); 109 | return this; 110 | } 111 | 112 | public Integer getSheetIndex() { 113 | return sheetIndex; 114 | } 115 | 116 | /** 117 | * @param sheetIndex 118 | * @return Config Config 119 | */ 120 | public Config setSheetIndex(Integer sheetIndex) { 121 | this.sheetIndex = sheetIndex; 122 | return this; 123 | } 124 | 125 | /** 126 | * @return String 127 | */ 128 | public String getSheetName() { 129 | return sheetName; 130 | } 131 | 132 | /** 133 | * @param sheetName 134 | * @return Config Config 135 | */ 136 | public Config setSheetName(String sheetName) { 137 | this.sheetName = sheetName; 138 | return this; 139 | } 140 | 141 | /** 142 | * 内容开始行号 143 | */ 144 | public Integer getTitleRow() { 145 | return titleRow; 146 | } 147 | 148 | /** 149 | * 标题行号 150 | */ 151 | public Config title(Integer titleRow) { 152 | this.titleRow = titleRow; 153 | return this; 154 | } 155 | 156 | /** 157 | * 内容开始行号 158 | */ 159 | public Integer getContentRowStart() { 160 | return contentRowStart; 161 | } 162 | 163 | /** 164 | * 内容开始行号 165 | * 166 | * @param contentRowStart contentRowStart 167 | */ 168 | public Config content(Integer contentRowStart) { 169 | this.contentRowStart = contentRowStart; 170 | return this; 171 | } 172 | 173 | /** 174 | * 内容结束行号 175 | * 176 | * @return 177 | */ 178 | public Integer getContentRowEnd() { 179 | return contentRowEnd; 180 | } 181 | 182 | public Map>> getConvertMap() { 183 | return convertMap; 184 | } 185 | 186 | public Map> getConvertMapImpl() { 187 | return convertMapImpl; 188 | } 189 | 190 | /** 191 | * 内容结束行号 192 | */ 193 | public Config contentRowEnd(Integer contentRowEnd) { 194 | this.contentRowEnd = contentRowEnd; 195 | return this; 196 | } 197 | 198 | public Boolean getIsLoopSheet() { 199 | return isLoopSheet; 200 | } 201 | 202 | public Config isLoopSheet(Boolean isLoopSheet) { 203 | this.isLoopSheet = isLoopSheet; 204 | return this; 205 | } 206 | 207 | public Integer getStartSheet() { 208 | return startSheet; 209 | } 210 | 211 | public Config startSheet(Integer startSheet) { 212 | this.startSheet = startSheet; 213 | return this; 214 | } 215 | 216 | public Integer getEndSheet() { 217 | return endSheet; 218 | } 219 | 220 | public Config endSheet(Integer endSheet) { 221 | this.endSheet = endSheet; 222 | return this; 223 | } 224 | 225 | @Override 226 | public String toString() { 227 | return "Config{" + "titleRow=" + titleRow + ", contentRowStart=" + contentRowStart + ", contentRowEnd=" + contentRowEnd + ", isLoopSheet=" + isLoopSheet + ", errorLog=" + errorLog + ", vocSize=" + vocSize + ", require=" + Arrays 228 | .toString(require) + ", startSheet=" + startSheet + ", endSheet=" + endSheet + '}'; 229 | } 230 | 231 | 232 | } -------------------------------------------------------------------------------- /src/main/java/seven/savewapper/wapperRef/SaveExcelObject.java: -------------------------------------------------------------------------------- 1 | package seven.savewapper.wapperRef; 2 | //======================================================= 3 | // .----. 4 | // _.'__ `. 5 | // .--(^)(^^)---/!\ 6 | // .' @ /!!!\ 7 | // : , !!!! 8 | // `-..__.-' _.-\!!!/ 9 | // `;_: `"' 10 | // .'"""""`. 11 | // /, ya ,\\ 12 | // //狗神保佑 \\ 13 | // `-._______.-' 14 | // ___`. | .'___ 15 | // (______|______) 16 | //======================================================= 17 | 18 | import org.apache.poi.ss.usermodel.Cell; 19 | import org.apache.poi.ss.usermodel.Row; 20 | import org.apache.poi.ss.usermodel.Workbook; 21 | import seven.callBack.*; 22 | import seven.callBack.imp.DefaultDataFilter; 23 | import seven.callBack.imp.DefaultDataProFilter; 24 | import seven.savewapper.SaveExcel; 25 | import seven.savewapper.cellStyle.CellStyle; 26 | import seven.util.ExcelTool; 27 | 28 | import java.io.FileOutputStream; 29 | import java.io.OutputStream; 30 | import java.sql.ResultSet; 31 | import java.util.ArrayList; 32 | import java.util.Comparator; 33 | import java.util.HashMap; 34 | import java.util.List; 35 | import java.util.function.Consumer; 36 | 37 | /** 38 | * [Zhihu]https://www.zhihu.com/people/Sweets07 39 | * [Github]https://github.com/MatrixSeven 40 | * Created by seven on 2016/11/30. 41 | */ 42 | public abstract class SaveExcelObject implements SaveExcel { 43 | protected List list; 44 | public static final String DEFAULT_TYPE = "xlsx"; 45 | protected String path; 46 | protected List filterColByKey = new ArrayList<>(); 47 | protected List anyColByKey = new ArrayList<>(); 48 | protected DataFilterInterface filter = new DefaultDataFilter(); 49 | protected DataFilterProcessInterface process = new DefaultDataProFilter(); 50 | protected Comparator c = null; 51 | protected ResultSet resultSet = null; 52 | protected OutputStream stream = null; 53 | protected Workbook wk = null; 54 | protected HashMap convertTitle = new HashMap<>(); 55 | protected HashMap cellStyle = new HashMap<>(); 56 | private List cellStyleCallbackWrappers = new ArrayList<>(); 57 | 58 | 59 | public SaveExcelObject(List list, String path) { 60 | this.list = list; 61 | this.path = path; 62 | } 63 | 64 | public SaveExcelObject(List list) { 65 | this.list = list; 66 | } 67 | 68 | public SaveExcelObject(ResultSet resultSet, String path) { 69 | this.resultSet = resultSet; 70 | this.path = path; 71 | } 72 | 73 | public SaveExcelObject(ResultSet resultSet) { 74 | this.resultSet = resultSet; 75 | } 76 | 77 | @Override 78 | public SaveExcelObject Filter(DataFilterInterface filter) { 79 | this.filter = filter; 80 | return this; 81 | } 82 | 83 | protected Workbook createWK() throws Exception { 84 | return wk != null ? wk : (wk = ExcelTool.newInstance(path.equals("") ? DEFAULT_TYPE : path, true)); 85 | } 86 | 87 | @Override 88 | public SaveExcelObject Process(DataFilterProcessInterface process) { 89 | this.process = process; 90 | return this; 91 | } 92 | 93 | @Override 94 | public SaveExcelObject Sort(Comparator c) { 95 | this.c = c; 96 | return this; 97 | } 98 | 99 | @Override 100 | public SaveExcelObject FilterCol(Consumer> df) { 101 | df.accept(filterColByKey); 102 | return this; 103 | } 104 | 105 | protected void checkData() throws Exception { 106 | if (this.list.isEmpty()) { 107 | throw new Exception("数据为空,请检查数据源"); 108 | } 109 | } 110 | 111 | protected OutputStream createStream() throws Exception { 112 | if (stream == null) { 113 | if (path == null || path.equals("")) 114 | throw new Exception("请输入路径"); 115 | return new FileOutputStream(path); 116 | } 117 | return stream; 118 | } 119 | 120 | protected String convertTitle(String title) throws Exception { 121 | String title_ = convertTitle.get(title); 122 | return title_ == null ? title : title_; 123 | } 124 | 125 | @Override 126 | public SaveExcel SetOutputStream(OutputStream stream) throws Exception { 127 | this.stream = stream; 128 | return this; 129 | } 130 | 131 | @Override 132 | public void Flush() throws Exception { 133 | this.Save(); 134 | } 135 | 136 | @Override 137 | public SaveExcel SetPath(String path) { 138 | this.path = path; 139 | return this; 140 | } 141 | 142 | @Override 143 | public SaveExcel ConvertName(String title, String newTitle) { 144 | convertTitle.put(title, newTitle); 145 | return this; 146 | } 147 | 148 | @Override 149 | public SaveExcel ConvertName(HashMap titleMapping) { 150 | convertTitle.putAll(titleMapping); 151 | return this; 152 | } 153 | 154 | @Override 155 | public SaveExcel ConvertName(HashMap titleMapping, Boolean isInit) { 156 | if (isInit) { 157 | convertTitle.clear(); 158 | } 159 | return ConvertName(titleMapping); 160 | } 161 | 162 | @Override 163 | public SaveExcel SetCellStyle(String name, CellStyleInterface styleInterface) { 164 | if (wk == null) { 165 | cellStyleCallbackWrappers.add(new CellStyleCallbackWrapper(name, styleInterface)); 166 | return this; 167 | } 168 | cellStyle.put(name, styleInterface.create(CellStyle.CreateStyle(wk.createCellStyle()))); 169 | return this; 170 | } 171 | 172 | protected void tryCreateCellStyle() throws Exception { 173 | if (wk == null) { 174 | throw new Exception("请输入路径并且初始化WK对象"); 175 | } 176 | for (CellStyleCallbackWrapper c : cellStyleCallbackWrappers) { 177 | c.create(wk, cellStyle); 178 | } 179 | } 180 | 181 | @Override 182 | public SaveExcel AnyCol(Consumer> df) { 183 | df.accept(this.anyColByKey); 184 | return this; 185 | } 186 | 187 | 188 | protected void initTitle(String[] title, Row row, org.apache.poi.ss.usermodel.CellStyle defStyle) throws Exception { 189 | for (short i = 0; i < title.length; i++) { 190 | Cell cell = row.createCell(i); 191 | cell.setCellStyle(defStyle); 192 | if (cellStyle.containsKey(title[i])) { 193 | cell.setCellStyle(cellStyle.get(title[i]).getRealyStyle()); 194 | } 195 | cell.setCellValue(convertTitle(title[i])); 196 | } 197 | } 198 | 199 | } 200 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/wapperRef/sysWppers/ResWrapperMap.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt.wapperRef.sysWppers; 2 | 3 | import org.apache.poi.ss.usermodel.Row; 4 | import org.apache.poi.ss.usermodel.Sheet; 5 | import org.apache.poi.ss.usermodel.Workbook; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import seven.util.ExcelTool; 9 | import seven.util.RegHelper; 10 | import seven.wapperInt.wapperRef.WrapperMap; 11 | 12 | import java.util.*; 13 | import java.util.function.Consumer; 14 | 15 | //======================================================= 16 | // .----. 17 | // _.'__ `. 18 | // .--(^)(^^)---/#\ 19 | // .' @ /###\ 20 | // : , ##### 21 | // : , ##### 22 | // `-..__.-' _.-\###/ 23 | // `;_: `"' 24 | // .'"""""`. 25 | // /, ya ,\\ 26 | // //狗神保佑 \\ 27 | // `-._______.-' 28 | // ___`. | .'___ 29 | // (______|______) 30 | //======================================================= 31 | 32 | /** 33 | * @author Seven 34 | */ 35 | @SuppressWarnings({"all"}) 36 | public class ResWrapperMap extends WrapperMap { 37 | 38 | private static final Logger logger = LoggerFactory.getLogger(ResWrapperMap.class); 39 | 40 | public ResWrapperMap(Consumer consumer) { 41 | super(consumer); 42 | } 43 | 44 | @Override 45 | protected T refResWrapper(String fs, boolean isMap) throws Exception { 46 | config.check(); 47 | HashMap> maps = null; 48 | List list = null; 49 | //TODO fix 50 | if (isMap) { 51 | maps = new HashMap<>(config.getVocSize()); 52 | } else { 53 | list = new ArrayList<>(config.getVocSize()); 54 | } 55 | 56 | Map map; 57 | String[] titles; 58 | Sheet sheet; 59 | Row row; 60 | String[] require = config.getRequire(); 61 | Workbook hhf = ExcelTool.newInstance(fs, false); 62 | int start_sheet = config.getStartSheet(); 63 | int end_sheet = start_sheet + 1; 64 | if (config.getIsLoopSheet()) { 65 | end_sheet = config.getEndSheet() == null ? hhf.getNumberOfSheets() : config.getEndSheet(); 66 | if (end_sheet <= 0 || end_sheet > hhf.getNumberOfSheets()) { 67 | logger.error("sheet范围不正确"); 68 | throw new Exception("sheet范围不正确"); 69 | } 70 | } 71 | 72 | 73 | if (config.getSheetName() != null) { 74 | boolean f=false; 75 | for (; start_sheet < end_sheet; start_sheet++) { 76 | sheet = hhf.getSheetAt(start_sheet); 77 | String sheetName = sheet.getSheetName().trim(); 78 | if (sheetName.equals(config.getSheetName().trim())) { 79 | f=true; 80 | break; 81 | } 82 | } 83 | if(!f){ 84 | throw new RuntimeException("输入Sheet名称有误"); 85 | } 86 | } 87 | 88 | if (config.getSheetIndex() != -1) { 89 | start_sheet = config.getSheetIndex(); 90 | end_sheet = start_sheet + 1; 91 | } 92 | 93 | Map sheetMap = new HashMap<>(); 94 | for (; start_sheet < end_sheet; start_sheet++) { 95 | sheet = hhf.getSheetAt(start_sheet); 96 | row = sheet.getRow(config.getTitleRow()); 97 | titles = new String[row.getPhysicalNumberOfCells()]; 98 | for (int i = 0, rows = row.getPhysicalNumberOfCells(); i < rows; i++) { 99 | titles[i] = getCellFormatValue(row.getCell((short) i)).toString(); 100 | } 101 | try { 102 | if (row.getPhysicalNumberOfCells() == 0) { 103 | logger.error("列表头获取失败"); 104 | throw new Exception("列表头获取失败"); 105 | } 106 | } catch (Exception e) { 107 | logger.error("列表头获取失败,sheet:{} sheetNmae:{}", start_sheet, sheet.getSheetName()); 108 | continue; 109 | } 110 | 111 | int start = config.getContentRowStart(); 112 | int rowNum = Objects.isNull(config.getContentRowEnd()) ? sheet.getLastRowNum() : config.getContentRowEnd(); 113 | for (; start < rowNum; start++) { 114 | row = sheet.getRow(start); 115 | String Map_key = ""; 116 | if (null != row) { 117 | map = new HashMap<>(); 118 | try { 119 | if (titles.length < row.getPhysicalNumberOfCells()) { 120 | logger.error("列表长度小于实际列长度"); 121 | throw new Exception("列表长度小于实际列长度"); 122 | } 123 | if (require != null && (titles.length != require.length)) { 124 | logger.error("验证规则长度不对"); 125 | throw new Exception("验证规则长度不对"); 126 | } 127 | } catch (Exception e) { 128 | logger.error("列表长度小于实际列长度 startSheet:{},sheetName:{}, row:{}", start_sheet, sheet.getSheetName(), rowNum); 129 | } 130 | for (int j = 0, colNum = row.getPhysicalNumberOfCells(); j < colNum && j < titles.length; j++) { 131 | if (require != null && !(require[j].equals("Null")) && !filterColByKey.contains(titles[j])) { 132 | if (RegHelper.require(require[j], getCellFormatValue(row.getCell((short) j)).toString())) { 133 | map.put(titles[j], getCellFormatValue(row.getCell((short) j)).toString()); 134 | } else { 135 | } 136 | } else { 137 | if (!filterColByKey.contains(titles[j])) { 138 | map.put(titles[j], getCellFormatValue(row.getCell((short) j)).toString()); 139 | } 140 | } 141 | } 142 | if (!isNull(map)) if (!this.filter.test(map)) { 143 | continue; 144 | } 145 | this.process.accept(map); 146 | if (isMap) { 147 | //maps.put(map.get(key), map); 148 | } else { 149 | list.add(map); 150 | } 151 | 152 | } 153 | } 154 | if (config.getIsLoopSheet()) { 155 | sheetMap.put(sheet.getSheetName(), list); 156 | list = new ArrayList<>(); 157 | } 158 | } 159 | if (config.getIsLoopSheet()) { 160 | return (T) sheetMap; 161 | } 162 | if (!isMap) { 163 | if (c != null) { 164 | list.sort(c); 165 | } 166 | return (T) list; 167 | } 168 | return (T) maps; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /src/main/java/seven/ExcelFactory.java: -------------------------------------------------------------------------------- 1 | package seven; 2 | 3 | import seven.callBack.PackageDataInterface; 4 | import seven.config.Config; 5 | import seven.savewapper.SaveExcel; 6 | import seven.savewapper.wapperRef.sysWppers.ResExportDBMap; 7 | import seven.savewapper.wapperRef.sysWppers.ResExportDBObj; 8 | import seven.savewapper.wapperRef.sysWppers.ResExportMap; 9 | import seven.savewapper.wapperRef.sysWppers.ResExportObj; 10 | import seven.wapperInt.ReaderMap; 11 | import seven.wapperInt.ReaderObj; 12 | import seven.wapperInt.wapperRef.sysWppers.ResWrapperMap; 13 | import seven.wapperInt.wapperRef.sysWppers.ResWrapperObj; 14 | 15 | import java.io.File; 16 | import java.sql.ResultSet; 17 | import java.util.List; 18 | import java.util.Map; 19 | import java.util.function.Consumer; 20 | 21 | 22 | //======================================================= 23 | // .----. 24 | // _.'__ `. 25 | // .--(^)(^^)---/#\ 26 | // .' @ /###\ 27 | // : , ##### 28 | // `-..__.-' _.-\###/ 29 | // `;_: `"' 30 | // .'"""""`. 31 | // /, ya ,\\ 32 | // //狗神保佑 \\ 33 | // `-._______.-' 34 | // ___`. | .'___ 35 | // (______|______) 36 | //======================================================= 37 | 38 | /** 39 | * @author Seven

40 | * date 2016年6月4日-下午4:08:19 41 | */ 42 | @SuppressWarnings("all") 43 | public class ExcelFactory { 44 | 45 | private ExcelFactory() { 46 | } 47 | 48 | /** 49 | * 读取Excel 50 | * 51 | * @param FilePath 路径 52 | * @return Wrapper 53 | * @throws Exception Exception 54 | */ 55 | public static ReaderMap getMaps(String FilePath) throws Exception { 56 | return (ReaderMap) new ResWrapperMap(it->{}).init(FilePath); 57 | } 58 | 59 | /** 60 | * 读取Excel 61 | * 62 | * @param FilePath 路径 63 | * @return Wrapper 64 | * @throws Exception Exception 65 | */ 66 | public static ReaderObj getBeans(Class clazz,String FilePath) throws Exception { 67 | return new ResWrapperObj(clazz,it->{}).init(FilePath); 68 | } 69 | 70 | /** 71 | * 读取Excel 72 | * 73 | * @param FilePath 路径 74 | * @param r 包装类 75 | * @return Wrapper 76 | * @throws Exception Exception 77 | */ 78 | public static ReaderMap getMaps(String FilePath, Consumer config) throws Exception { 79 | return (ReaderMap) new ResWrapperMap(config).init(FilePath); 80 | } 81 | 82 | /** 83 | * 读取Excel 84 | * 85 | * @param FilePath 路径 86 | * @param clazz clazz 87 | * @param config config 88 | * @param t 89 | * @return Wrapper 90 | * @throws Exception 91 | */ 92 | public static ReaderObj getBeans(Class clazz,String FilePath, Consumer config) throws Exception { 93 | return new ResWrapperObj(clazz, config).init(FilePath); 94 | } 95 | 96 | /** 97 | * 读取Excel 98 | * @param file file 99 | * @return Wrapper 100 | * @throws Exception Exception 101 | */ 102 | public static ReaderMap getMaps(File file) throws Exception { 103 | return (ReaderMap) new ResWrapperMap(it->{}).init(file); 104 | } 105 | 106 | /** 107 | * 读取Excel 108 | * @param clazz clazz 109 | * @param file file 110 | * @param T 111 | * @return Wrapper 112 | * @throws Exception Exception 113 | */ 114 | public static ReaderObj getBeans(Class clazz,File file) throws Exception { 115 | return new ResWrapperObj(clazz,it->{}).init(file); 116 | } 117 | 118 | /** 119 | * 读取Excel 120 | * @param file file 121 | * @param config config 122 | * @return Wrapper 123 | * @throws Exception Exception 124 | */ 125 | public static ReaderMap getMaps(File file, Consumer config) throws Exception { 126 | return (ReaderMap) new ResWrapperMap(config).init(file); 127 | } 128 | 129 | 130 | /** 131 | * 读取Excel 132 | * @param clazz clazz 133 | * @param file file 134 | * @param config config 135 | * @param 136 | * @return T 137 | * @throws Exception Exception 138 | */ 139 | public static ReaderObj getBeans(Class clazz,File file, Consumer config) throws Exception { 140 | return new ResWrapperObj(clazz, config).init(file); 141 | } 142 | 143 | /** 144 | * 保存Excel 145 | * @param T 146 | * @param bean bean 147 | * @param FilePath FilePath 148 | * @return SaveExcel 149 | * @throws Exception Exception 150 | */ 151 | public static SaveExcel saveExcel(List bean, String FilePath) throws Exception { 152 | if (bean.size() < 1) { 153 | throw new Exception("请传入数据"); 154 | } 155 | if (bean.get(0) instanceof Map) { 156 | return (SaveExcel) new ResExportMap((List) bean, FilePath); 157 | } 158 | return new ResExportObj(bean, FilePath); 159 | } 160 | 161 | /** 162 | * 保存Excel 163 | * 164 | * @param bean bean 165 | * @return SaveExcel 166 | * @throws Exception Exception 167 | */ 168 | public static SaveExcel saveExcel(List bean) throws Exception { 169 | if (bean.size() < 1) { 170 | throw new Exception("请传入数据"); 171 | } 172 | if (bean.get(0) instanceof Map) { 173 | return new ResExportMap((List) bean); 174 | } 175 | return new ResExportObj((List) bean); 176 | } 177 | 178 | 179 | /** 180 | * 保存Excel 181 | * 182 | * @param resultSet resultSet 183 | * @param FilePath FilePath 184 | * @return SaveExcel 185 | * @throws Exception Exception 186 | */ 187 | public static SaveExcel saveExcel(ResultSet resultSet, String FilePath) throws Exception { 188 | return new ResExportDBMap(resultSet, FilePath); 189 | } 190 | 191 | /** 192 | * 保存Excel 193 | * 194 | * @param resultSet resultSet 195 | * @param FilePath FilePath 196 | * @param packageDataInterface packageDataInterface 197 | * @return SaveExcel 198 | * @throws Exception Exception 199 | */ 200 | public static SaveExcel saveExcel(ResultSet resultSet, String FilePath, PackageDataInterface packageDataInterface) throws Exception { 201 | return new ResExportDBObj(resultSet, FilePath, packageDataInterface); 202 | } 203 | 204 | /** 205 | * 保存Excel 206 | * 207 | * @param resultSet resultSet 208 | * @param type type 209 | * @return SaveExcel 210 | * @throws Exception Exception 211 | */ 212 | public static SaveExcel saveExcel(ResultSet resultSet, Class type) throws Exception { 213 | return new ResExportDBObj(resultSet, type); 214 | } 215 | 216 | 217 | /** 218 | * 保存Excel 219 | * 220 | * @param resultSet resultSet 221 | * @return SaveExcel 222 | * @throws Exception Exception 223 | */ 224 | public static SaveExcel saveExcel(ResultSet resultSet) throws Exception { 225 | return new ResExportDBMap(resultSet); 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /src/main/java/seven/wapperInt/wapperRef/sysWppers/ResWrapperObj.java: -------------------------------------------------------------------------------- 1 | package seven.wapperInt.wapperRef.sysWppers; 2 | 3 | import org.apache.poi.ss.usermodel.Row; 4 | import org.apache.poi.ss.usermodel.Sheet; 5 | import org.apache.poi.ss.usermodel.Workbook; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | import seven.anno.ExcelAnno; 9 | import seven.callBack.ConvertInterface; 10 | import seven.config.Config; 11 | import seven.handler.InPutHandler; 12 | import seven.handler.HandlerFactory; 13 | import seven.util.ExcelTool; 14 | import seven.util.RegHelper; 15 | import seven.wapperInt.wapperRef.WrapperObj; 16 | 17 | import java.lang.reflect.*; 18 | import java.util.*; 19 | import java.util.function.Consumer; 20 | 21 | //======================================================= 22 | // .----. 23 | // _.'__ `. 24 | // .--(^)(^^)---/#\ 25 | // .' @ /###\ 26 | // : , ##### 27 | // `-..__.-' _.-\###/ 28 | // `;_: `"' 29 | // .'"""""`. 30 | // /, ya ,\\ 31 | // //狗神保佑 \\ 32 | // `-._______.-' 33 | // ___`. | .'___ 34 | // (______|______) 35 | //======================================================= 36 | 37 | /** 38 | * @author Seven

39 | * 2016年6月4日-下午4:07:14 40 | */ 41 | @SuppressWarnings({"all"}) 42 | public class ResWrapperObj extends WrapperObj { 43 | private static final Logger logger = LoggerFactory.getLogger(ResWrapperObj.class); 44 | 45 | private static R Try(Class clazz) { 46 | try { 47 | return (R) clazz.newInstance(); 48 | } catch (Exception ex) { 49 | ex.printStackTrace(); 50 | } 51 | logger.warn("数据转化注册失败,{},放弃处理", clazz); 52 | return null; 53 | } 54 | 55 | @Override 56 | protected T refResWrapper(String fs, boolean isMap) throws Exception { 57 | config.check(); 58 | HashMap FieldCaChe = new HashMap<>(); 59 | List data = null; 60 | Map> map = new HashMap<>(); 61 | Constructor[] constructors = type.getConstructors(); 62 | Field[] F = type.getDeclaredFields(); 63 | ExcelAnno Ex = null; 64 | String[] reg = new String[F.length]; 65 | Arrays.fill(reg, "Null"); 66 | int reg_index = 0; 67 | Field Map_key = null; 68 | data = new ArrayList(config.getVocSize()); 69 | Map convertMap = new HashMap<>(); 70 | for (Field f : F) { 71 | f.setAccessible(true); 72 | if ((Ex = f.getAnnotation(ExcelAnno.class)) != null && !Ex.Pass()) { 73 | reg[reg_index++] = Ex.Required(); 74 | FieldCaChe.put(Ex.Value(), f); 75 | if (Ex.Convert() != null) { 76 | convertMap.put(Ex.Value(), Try(Ex.Convert())); 77 | } 78 | } else { 79 | FieldCaChe.put(f.getName(), f); 80 | } 81 | } 82 | config.getConvertMap().forEach((k, v) -> { 83 | convertMap.put(k, Try(v)); 84 | }); 85 | config.getConvertMapImpl().forEach((k, v) -> { 86 | convertMap.put(k, v); 87 | }); 88 | Constructor declaredConstructor = type.getDeclaredConstructor(); 89 | declaredConstructor.setAccessible(true); 90 | String[] titles; 91 | Sheet sheet; 92 | Row row; 93 | T o; 94 | String v; 95 | int start_sheet = config.getStartSheet(); 96 | Workbook hhf = ExcelTool.newInstance(fs, false); 97 | ; 98 | int end_sheet = start_sheet + 1; 99 | if (config.getIsLoopSheet()) { 100 | map = new HashMap<>(); 101 | end_sheet = config.getEndSheet() == null ? hhf.getNumberOfSheets() : config.getEndSheet(); 102 | if (end_sheet <= 0 || end_sheet > hhf.getNumberOfSheets()) { 103 | logger.error("sheet范围不正确"); 104 | throw new Exception("sheet范围不正确"); 105 | } 106 | } 107 | sheet = hhf.getSheetAt(start_sheet); 108 | row = sheet.getRow(config.getTitleRow()); 109 | titles = new String[row.getPhysicalNumberOfCells()]; 110 | for (int i = 0, rows = row.getPhysicalNumberOfCells(); i < rows; i++) { 111 | titles[i] = getCellFormatValue(row.getCell((short) i)); 112 | } 113 | 114 | if (config.getIsLoopSheet()) { 115 | end_sheet = config.getEndSheet() == null ? hhf.getNumberOfSheets() : config.getEndSheet(); 116 | if (end_sheet <= 0 || end_sheet > hhf.getNumberOfSheets()) { 117 | logger.error("sheet范围不正确,sheet range:{}", config.getEndSheet()); 118 | throw new Exception("sheet范围不正确"); 119 | } 120 | } 121 | for (; start_sheet < end_sheet; start_sheet++) { 122 | sheet = hhf.getSheetAt(start_sheet); 123 | int start = config.getContentRowStart(); 124 | for (int rowNum = sheet.getLastRowNum(); start <= rowNum; start++) { 125 | row = sheet.getRow(start); 126 | if (null != row) { 127 | o = (T) declaredConstructor.newInstance(); 128 | for (int j = 0, colNum = row.getPhysicalNumberOfCells(); j < colNum; j++) { 129 | if (FieldCaChe.containsKey(titles[j]) && !this.filterColByKey.contains(titles[j])) { 130 | ConvertInterface orDefault = convertMap.get(titles[j]); 131 | Field field = FieldCaChe.get(titles[j]); 132 | String cellFormatValue = getCellFormatValue(row.getCell((short) j)); 133 | InPutHandler handlerType = HandlerFactory.getInPutHandler(field.getType()); 134 | if (!reg[j].equals("Null")) { 135 | if (RegHelper.require(reg[j], v = cellFormatValue)) { 136 | field.set(o, handlerType.Handler(v)); 137 | // if (Objects.isNull(orDefault)) { 138 | // field.set(o, handlerType.Handler(v)); 139 | // } else { 140 | // field.set(o, orDefault.convert(v)); 141 | // }; 142 | } else { 143 | logger.warn("数据格 {} 式不符合规范---->行:{} 列:{}", titles[j], start, j); 144 | } 145 | } else { 146 | field.set(o, handlerType.Handler(cellFormatValue)); 147 | // if (Objects.isNull(orDefault)) { 148 | // field.set(o, handlerType.Handler(cellFormatValue)); 149 | // } else { 150 | // field.set(o, orDefault.convert(cellFormatValue)); 151 | // }; 152 | } 153 | } 154 | } 155 | if (!this.filter.test(o)) { 156 | continue; 157 | } 158 | process.accept(o); 159 | data.add((T) o); 160 | } 161 | } 162 | 163 | map.put(sheet.getSheetName(), data); 164 | data = new ArrayList<>(); 165 | 166 | 167 | } 168 | 169 | if (c != null) { 170 | data.sort(c); 171 | } 172 | if (config.getIsLoopSheet()) { 173 | return (T) map; 174 | } 175 | return (T) data; 176 | 177 | 178 | } 179 | 180 | private Class type; 181 | 182 | public ResWrapperObj(Class clazz, Consumer consumer) { 183 | super(consumer); 184 | this.type = clazz; 185 | 186 | } 187 | 188 | //public ResWrapperObj(Consumer consumer) { 189 | // super(consumer); 190 | // Type sType = getClass().getGenericSuperclass(); 191 | // Type[] generics = ((ParameterizedType) sType).getActualTypeArguments(); 192 | // Class mTClass = (Class) (generics[0]); 193 | // try { 194 | // type = mTClass.newInstance(); 195 | // } catch (Exception e) { 196 | // e.printStackTrace(); 197 | // } 198 | //} 199 | } 200 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------