├── CNAME ├── _config.yml ├── excel ├── .gitignore └── src │ ├── test │ ├── resources │ │ ├── person.xls │ │ ├── person.xlsx │ │ ├── salary.xlsx │ │ ├── salary4.xlsx │ │ ├── salary6.xls │ │ ├── salary6.xlsx │ │ ├── salary7.xlsx │ │ └── salaryEvent.xlsx │ └── java │ │ └── com │ │ └── chinamobile │ │ ├── excel │ │ ├── WriteHandlerTest.java │ │ ├── SaxReaderTest1.java │ │ ├── WriteTest3.java │ │ ├── ReadTest4.java │ │ ├── WriteTest1.java │ │ ├── ReadTest.java │ │ ├── ReadTest7.java │ │ ├── ReadTest8.java │ │ ├── ReadTestGlobalConverter6.java │ │ ├── ReadTestEventModel5.java │ │ ├── ReadTest2.java │ │ ├── ReadTest3.java │ │ ├── WriteTest2.java │ │ ├── WriteTest4.java │ │ ├── WriteTestSheetExcel.java │ │ ├── WriteTest5.java │ │ └── WriteTest6.java │ │ └── other │ │ ├── TestTest.java │ │ ├── CSVTest.java │ │ ├── AnotationTest.java │ │ ├── LinkedTest.java │ │ ├── ReadTestThreadLocal.java │ │ ├── ReadTestThreadLocalGC.java │ │ └── MyTest.java │ └── main │ └── java │ └── com │ └── bing │ ├── excel │ ├── core │ │ ├── BingReadListener.java │ │ ├── rw │ │ │ └── BingWriterHandler.java │ │ ├── handler │ │ │ ├── ConverterHandler.java │ │ │ └── LocalConverterHandler.java │ │ ├── BingExcelEvent.java │ │ ├── common │ │ │ └── FieldRelation.java │ │ ├── ReaderCondition.java │ │ ├── BingExcelEventBuilder.java │ │ ├── BingExcelBuilder.java │ │ └── BingExcel.java │ ├── mapper │ │ ├── AnnotationMapper.java │ │ ├── ExcelConverterMapperHandler.java │ │ ├── UserDefineMapperHandler.java │ │ ├── ConversionMapperBuilder.java │ │ ├── BaseGlobalConverterMapper.java │ │ └── ConversionMapper.java │ ├── converter │ │ ├── HeaderReflectConverter.java │ │ ├── ModelAdapter.java │ │ ├── ConverterMatcher.java │ │ ├── base │ │ │ ├── StringFieldConverter.java │ │ │ ├── DoubleFieldConverter.java │ │ │ ├── FloatFieldConverter.java │ │ │ ├── LongFieldConverter.java │ │ │ ├── CharacterFieldConverter.java │ │ │ ├── ShortFieldConverter.java │ │ │ ├── ByteFieldConverter.java │ │ │ ├── IntegerFieldConverter.java │ │ │ ├── BooleanFieldConverter.java │ │ │ └── DateFieldConverter.java │ │ ├── FieldValueConverter.java │ │ ├── AbstractFieldConvertor.java │ │ ├── enums │ │ │ └── EnumConVerter.java │ │ └── collections │ │ │ ├── ArrayConverter.java │ │ │ └── CollectionConverter.java │ ├── writer │ │ ├── exception │ │ │ └── ExcelOutException.java │ │ ├── WriteHandler.java │ │ ├── DefaultFileWriteHandler.java │ │ ├── DefaultStreamWriteHandler.java │ │ ├── SXSSFWriterHandler.java │ │ └── ExcelWriterFactory.java │ ├── exception │ │ ├── InitializationException.java │ │ ├── MissingCellConfigException.java │ │ ├── ConversionException.java │ │ ├── illegalValueException.java │ │ ├── BingSaxReadStopException.java │ │ ├── IllegalCellConfigException.java │ │ └── IllegalEntityException.java │ ├── reader │ │ ├── AbstractExcelReadListener.java │ │ ├── ExcelReadListener.java │ │ ├── ReadHandler.java │ │ ├── usermodel │ │ │ ├── ExcelHSSFDataFormatter.java │ │ │ └── ExcelHSSFDataFormat.java │ │ ├── hssf │ │ │ ├── DefaultHSSFHandler.java │ │ │ └── ExcelFormatTrackingHSSFListener.java │ │ ├── sax │ │ │ └── ExcelReadOnlySharedStringsTable.java │ │ └── ExcelReaderFactory.java │ ├── annotation │ │ ├── OutAlias.java │ │ ├── BingConvertor.java │ │ └── CellConfig.java │ └── vo │ │ ├── OutValue.java │ │ ├── CellKV.java │ │ ├── ListRow.java │ │ └── ListLine.java │ ├── common │ └── ExcleBuilder.java │ └── utils │ ├── FileCreateUtils.java │ ├── DataTypeDetect.java │ └── ReflectDependencyFactory.java ├── .gitignore └── README.md /CNAME: -------------------------------------------------------------------------------- 1 | excel.binging.com.cn 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /excel/.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .classpath 3 | .project 4 | /.metadata 5 | /.settings 6 | *.iml 7 | /.idea 8 | 9 | -------------------------------------------------------------------------------- /excel/src/test/resources/person.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/person.xls -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | .classpath 3 | .project 4 | /.metadata 5 | /.settings 6 | /WebRoot/WEB-INF/classes 7 | /WebRoot/WEB-INF/lib -------------------------------------------------------------------------------- /excel/src/test/resources/person.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/person.xlsx -------------------------------------------------------------------------------- /excel/src/test/resources/salary.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salary.xlsx -------------------------------------------------------------------------------- /excel/src/test/resources/salary4.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salary4.xlsx -------------------------------------------------------------------------------- /excel/src/test/resources/salary6.xls: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salary6.xls -------------------------------------------------------------------------------- /excel/src/test/resources/salary6.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salary6.xlsx -------------------------------------------------------------------------------- /excel/src/test/resources/salary7.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salary7.xlsx -------------------------------------------------------------------------------- /excel/src/test/resources/salaryEvent.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bingyulei007/bingexcel/HEAD/excel/src/test/resources/salaryEvent.xlsx -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/BingReadListener.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | import com.bing.excel.core.impl.BingExcelEventImpl; 4 | 5 | @Deprecated 6 | public interface BingReadListener { 7 | 8 | void readModel(Object object, BingExcelEventImpl.ModelInfo modelInfo); 9 | 10 | } 11 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/AnnotationMapper.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | public interface AnnotationMapper { 4 | 5 | /** 6 | * 注册转换类实体 7 | */ 8 | void processEntity(final Class[] initialTypes); 9 | 10 | /** 11 | * 注册转换类实体 12 | */ 13 | void processEntity(final Class initialType); 14 | } 15 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/HeaderReflectConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter; 2 | 3 | import java.util.List; 4 | 5 | import com.bing.excel.mapper.ExcelConverterMapperHandler; 6 | import com.bing.excel.vo.CellKV; 7 | 8 | 9 | public interface HeaderReflectConverter { 10 | List> getHeader(ExcelConverterMapperHandler... handler); 11 | } 12 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/rw/BingWriterHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core.rw; 2 | 3 | 4 | public interface BingWriterHandler { 5 | /** 6 | * 写入对象到excel表,默认同种对象在同一个sheet页面,不同对象另起新的sheet 7 | * @param obj 8 | */ 9 | void writeLine(Object obj); 10 | 11 | /** 12 | * 单页最大行数 13 | * @param max 14 | */ 15 | void setMaxLineForSheet(int max); 16 | /** 17 | * 输出文件。 18 | */ 19 | void close(); 20 | } 21 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/writer/exception/ExcelOutException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.writer.exception; 2 | 3 | public class ExcelOutException extends RuntimeException { 4 | 5 | public ExcelOutException(String message, Throwable cause) { 6 | super(message, cause); 7 | } 8 | 9 | public ExcelOutException(String message) { 10 | super(message); 11 | } 12 | 13 | public ExcelOutException(Throwable cause) { 14 | super(cause); 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/InitializationException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | 3 | /** 4 | * @author shizhongtao 5 | * 6 | */ 7 | public class InitializationException extends RuntimeException { 8 | 9 | public InitializationException(String message, Throwable cause) { 10 | super(message, cause); 11 | } 12 | 13 | public InitializationException(String message) { 14 | super(message); 15 | } 16 | 17 | public InitializationException(Throwable cause) { 18 | super(cause); 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/MissingCellConfigException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | 3 | /** 4 | * 当用户定义实体缺少CellConfig注解时候抛出 5 | * @author shizhongtao 6 | * 7 | */ 8 | public class MissingCellConfigException extends IllegalEntityException { 9 | 10 | 11 | 12 | public MissingCellConfigException(String message, Throwable cause) { 13 | super(message, cause); 14 | } 15 | 16 | public MissingCellConfigException(String message) { 17 | super(message); 18 | } 19 | 20 | public MissingCellConfigException(Throwable cause) { 21 | super(cause); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/ModelAdapter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter; 2 | 3 | 4 | import com.bing.excel.mapper.ExcelConverterMapperHandler; 5 | import com.bing.excel.vo.ListLine; 6 | import com.bing.excel.vo.ListRow; 7 | 8 | 9 | 10 | /** 11 | * 创建时间:2015-12-15下午2:12:56 12 | * 项目名称:excel 13 | * @author shizhongtao 14 | * @version 1.0 15 | * 文件名称:Convertor.java 16 | */ 17 | public interface ModelAdapter { 18 | ListLine marshal(Object source,ExcelConverterMapperHandler... handler); 19 | Object unmarshal(ListRow source, ExcelConverterMapperHandler... handler); 20 | } 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # bingExcel   2 | 3 |  [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg?style=flat-square)](https://www.apache.org/licenses/LICENSE-2.0.html) 4 | 5 | 处理excel与java model之间转换,想做成一个excel的orm类型的框架 6 | 具体使用说明可以参照 [开源中国wiki](https://git.oschina.net/bingyulei007/bingExcel/wikis/home), [github地址wiki](https://github.com/bingyulei007/bingExcel/wiki),当然wiki写的比较简单,大家可以fork下源码,里面有很多单元测试的例子。 7 | 8 | ## 环境说明 9 | 基于java1.7,依赖poi3.1X.jar包,commons-lang3 jar,com.google.guava 等 10 | 11 | ## 联系我 12 | 如果有问题可以留言,也可以发送邮件到 * _shizhongtao@gmail.com_ * 13 | 14 | PS:`另外由于目前项目是个人维护,所以在功能的增加上及维护上可能有点滞后,请谅解。` 15 | 16 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/ConverterMatcher.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter; 2 | 3 | 4 | /** 5 | *

Title: ConverterMatcher

6 | *

Description: ConverterMatcher is the base interface of any converter

7 | *

Company: chinamobile

8 | * 9 | * @author zhongtao.shi 10 | */ 11 | public interface ConverterMatcher { 12 | 13 | /** 14 | * Determines whether the converter can marshall a particular type. 15 | * @param clz the Class representing the object type to be converted 16 | * @return true or false 17 | */ 18 | boolean canConvert(Class clz); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/ExcelConverterMapperHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | import com.bing.excel.mapper.ConversionMapper.FieldConverterMapper; 5 | 6 | public interface ExcelConverterMapperHandler { 7 | 8 | 9 | ConversionMapper getObjConversionMapper(); 10 | 11 | @Deprecated 12 | FieldValueConverter getLocalConverter(Class definedIn, 13 | String fieldName); 14 | 15 | FieldConverterMapper getLocalFieldConverterMapper(Class definedIn, 16 | String fieldName); 17 | 18 | String getModelName(Class definedIn); 19 | 20 | } 21 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/StringFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.converter.AbstractFieldConvertor; 6 | import com.bing.excel.core.handler.ConverterHandler; 7 | 8 | public final class StringFieldConverter extends AbstractFieldConvertor { 9 | 10 | @Override 11 | public boolean canConvert(Class clz) { 12 | return clz.equals(String.class); 13 | } 14 | 15 | @Override 16 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 17 | return cell; 18 | } 19 | 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/writer/WriteHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.writer; 2 | 3 | import java.util.List; 4 | 5 | import com.bing.excel.vo.CellKV; 6 | import com.bing.excel.vo.ListLine; 7 | 8 | /** 9 | * 目前的三个实现不是线程安全的 10 | * @author shizhongtao 11 | * 12 | */ 13 | public interface WriteHandler { 14 | 15 | /** 16 | * 17 | */ 18 | public abstract void writeLine(ListLine line); 19 | public abstract void writeHeader(List> listStr); 20 | void writeHeader(ListLine listLine); 21 | public abstract String createSheet(String name); 22 | 23 | /** 24 | * 25 | */ 26 | public abstract void flush(); 27 | 28 | } 29 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/AbstractExcelReadListener.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader; 2 | 3 | 4 | import com.bing.excel.vo.ListRow; 5 | 6 | 7 | /** 8 | * @author shizhongtao 9 | * 10 | * date 2016-3-1 11 | * Description: 12 | */ 13 | public abstract class AbstractExcelReadListener implements ExcelReadListener { 14 | 15 | @Override 16 | public void optRow(int curRow, ListRow rowList) { 17 | 18 | } 19 | 20 | @Override 21 | public void startSheet(int sheetIndex, String name) { 22 | 23 | } 24 | 25 | @Override 26 | public void endSheet(int sheetIndex, String name) { 27 | 28 | } 29 | 30 | @Override 31 | public void endWorkBook() { 32 | 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/ConversionException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | /** 3 | * 创建时间:2015-12-16下午6:19:12 4 | * 项目名称:excel 5 | * @author shizhongtao 6 | * @version 1.0 7 | * @since JDK 1.7 8 | * 文件名称:ConvertorException.java 9 | * 类说明: 10 | */ 11 | public class ConversionException extends RuntimeException { 12 | 13 | public ConversionException() { 14 | super(); 15 | } 16 | 17 | public ConversionException(String message, Throwable cause) { 18 | super(message, cause); 19 | } 20 | 21 | public ConversionException(String message) { 22 | super(message); 23 | } 24 | 25 | public ConversionException(Throwable cause) { 26 | super(cause); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/annotation/OutAlias.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | 10 | 11 | /** 12 | * 创建时间:2015-12-8下午9:41:18 项目名称:excel 13 | * 14 | * @author shizhongtao 15 | * @version 1.0 16 | * @since JDK 1.7 文件名称:BingCell.java 类说明: 17 | */ 18 | @Target({ElementType.TYPE}) 19 | @Retention(RetentionPolicy.RUNTIME) 20 | @Documented 21 | public @interface OutAlias { 22 | 23 | /** 24 | * 输出时候的sheet名称 25 | * @return 名称 26 | */ 27 | public String value() default ""; 28 | } 29 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/FieldValueConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.vo.OutValue; 7 | 8 | 9 | 10 | /** 11 | * 创建时间:2015-12-15下午2:12:56 12 | * 项目名称:excel 13 | * @author shizhongtao 14 | * @version 1.0 15 | * 文件名称:FieldValueConverter.java 16 | * 类说明: 这里面convertor是针对实体类的filed。主要用于扩展转换,目前版本中,convertor中必须有无参的构造方法。 17 | */ 18 | public interface FieldValueConverter extends ConverterMatcher { 19 | OutValue toObject(Object source,ConverterHandler converterHandler); 20 | Object fromString(String cell,ConverterHandler converterHandler,Type targetType); 21 | } 22 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/illegalValueException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | /** 3 | * 创建时间:2015-12-15下午3:52:43 4 | * 项目名称:excel 5 | * @author shizhongtao 6 | * @version 1.0 7 | * @since JDK 1.7 8 | * 文件名称:ErrorValueException.java 9 | * 类说明: 10 | */ 11 | public class illegalValueException extends RuntimeException { 12 | 13 | /** 14 | * serialVersionUID 15 | */ 16 | private static final long serialVersionUID = 1L; 17 | 18 | public illegalValueException() { 19 | super("单元格数值非法"); 20 | } 21 | 22 | public illegalValueException(String message, Throwable cause) { 23 | super(message, cause); 24 | } 25 | 26 | public illegalValueException(String message) { 27 | super(message); 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/BingSaxReadStopException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | 3 | import org.xml.sax.SAXException; 4 | 5 | /** 6 | * @author shizhongtao 7 | * 8 | * date 2016-2-2 9 | * Description: this only a mark exception ,when you want to stop the sax 10 | * 11 | */ 12 | public class BingSaxReadStopException extends SAXException { 13 | 14 | /** 15 | * 16 | */ 17 | private static final long serialVersionUID = 1L; 18 | 19 | @Override 20 | public String getMessage() { 21 | return super.getMessage(); 22 | } 23 | 24 | @Override 25 | public String toString() { 26 | return super.toString(); 27 | } 28 | 29 | public BingSaxReadStopException(String message) { 30 | super(message); 31 | 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/ExcelReadListener.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader; 2 | 3 | 4 | import com.bing.excel.vo.ListRow; 5 | 6 | /** 7 | * @author shizhongtao 8 | * 9 | * date 2016-3-1 10 | * Description: 11 | */ 12 | public interface ExcelReadListener { 13 | /** 14 | * 该方法自动被调用,每读一行调用一次,在方法中写自己的业务逻辑即可 15 | * 16 | * @param sheetIndex 17 | * 工作簿序号 18 | * @param curRow 19 | * 处理到第几行 20 | * @param rowList 21 | * 当前数据行的数据集合 22 | */ 23 | void optRow(int curRow, ListRow rowList); 24 | void startSheet(int sheetIndex, String name); 25 | /** 26 | * @param sheetIndex 工作表下标 从0开始 27 | * @param name 工作表名称 28 | */ 29 | void endSheet(int sheetIndex, String name); 30 | void endWorkBook(); 31 | } 32 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/handler/ConverterHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core.handler; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | 5 | 6 | /** 7 | * @author shizhongtao 8 | * 9 | * date 2015-12-14 PM 4:44:52 10 | * Description: 11 | */ 12 | public interface ConverterHandler { 13 | 14 | 15 | /** 16 | * Get default FieldConverter which is difined by BaseGlobalConverterMapper or user. 17 | * @param keyFieldType 18 | * @return defaultConvetter or null 19 | */ 20 | FieldValueConverter getLocalConverter(Class keyFieldType); 21 | 22 | /** 23 | * Registe converter for this {@code Class} clazz. 24 | * @param clazz 25 | * @param converter 26 | */ 27 | void registerConverter(Class clazz, FieldValueConverter converter); 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/IllegalCellConfigException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | 3 | public class IllegalCellConfigException extends RuntimeException { 4 | 5 | /** 6 | * 7 | */ 8 | private static final long serialVersionUID = 1L; 9 | 10 | public IllegalCellConfigException() { 11 | super(); 12 | } 13 | 14 | public IllegalCellConfigException(String message, Throwable cause, 15 | boolean enableSuppression, boolean writableStackTrace) { 16 | super(message, cause, enableSuppression, writableStackTrace); 17 | } 18 | 19 | public IllegalCellConfigException(String message, Throwable cause) { 20 | super(message, cause); 21 | } 22 | 23 | public IllegalCellConfigException(String message) { 24 | super(message); 25 | } 26 | 27 | public IllegalCellConfigException(Throwable cause) { 28 | super(cause); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/AbstractFieldConvertor.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.vo.OutValue; 7 | 8 | public class AbstractFieldConvertor implements FieldValueConverter { 9 | 10 | @Override 11 | public boolean canConvert(Class clz) { 12 | 13 | return false; 14 | } 15 | 16 | @Override 17 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 18 | if(source==null){ 19 | return null; 20 | } 21 | return new OutValue(OutValue.OutType.STRING, source.toString()); 22 | } 23 | 24 | @Override 25 | public Object fromString(String cell, ConverterHandler converterHandler, 26 | Type targetType) { 27 | if (cell == null) { 28 | return null; 29 | } 30 | return cell; 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/common/ExcleBuilder.java: -------------------------------------------------------------------------------- 1 | package com.bing.common; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | import com.bing.excel.core.BingExcel; 5 | 6 | /** 7 | * @author shizhongtao 8 | * 9 | * Description: 10 | */ 11 | public interface ExcleBuilder { 12 | 13 | ExcleBuilder addFieldConversionMapper(Class clazz, 14 | String filedName, int index); 15 | 16 | ExcleBuilder addFieldConversionMapper(Class clazz, 17 | String filedName, int index, String alias); 18 | 19 | ExcleBuilder addFieldConversionMapper(Class clazz, 20 | String filedName, int index, String alias, FieldValueConverter converter); 21 | 22 | ExcleBuilder addClassNameAlias(Class clazz, 23 | String alias); 24 | 25 | /** 26 | * 由build()方法代替 27 | * @return 28 | */ 29 | @Deprecated 30 | T builder(); 31 | T build(); 32 | 33 | ExcleBuilder registerFieldConverter(Class clazz, 34 | FieldValueConverter converter); 35 | } 36 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteHandlerTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import com.bing.excel.vo.CellKV; 4 | import com.bing.excel.vo.ListLine; 5 | import com.bing.excel.writer.ExcelWriterFactory; 6 | import com.bing.excel.writer.WriteHandler; 7 | 8 | import org.junit.Test; 9 | 10 | import java.util.ArrayList; 11 | import java.util.Date; 12 | import java.util.List; 13 | 14 | /** 15 | * Created by szt on 2017/1/17. 16 | */ 17 | public class WriteHandlerTest { 18 | @Test 19 | public void test() { 20 | WriteHandler handler = ExcelWriterFactory.createXSSF("D:/aa.xlsx"); 21 | List> listStr=new ArrayList<>(); 22 | listStr.add(new CellKV(0, "diyi")); 23 | listStr.add(new CellKV(1, "date")); 24 | handler.createSheet("aa"); 25 | handler.writeHeader(listStr); 26 | Date date=null; 27 | String a=null; 28 | handler.writeLine(new ListLine().addValue(0, true).addValue(1,date).addValue(2,a)); 29 | handler.flush(); 30 | 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/TestTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.junit.Test; 7 | 8 | import com.bing.excel.vo.CellKV; 9 | import com.bing.excel.vo.ListLine; 10 | import com.bing.excel.writer.ExcelWriterFactory; 11 | import com.bing.excel.writer.WriteHandler; 12 | 13 | public class TestTest { 14 | @Test 15 | public void testme() { 16 | WriteHandler handler = ExcelWriterFactory.createSXSSF("E:/aoptest/big.xlsx"); 17 | List> listStr=new ArrayList<>(); 18 | listStr.add(new CellKV(0, "diyi")); 19 | handler.createSheet("aa"); 20 | handler.writeHeader(listStr); 21 | handler.writeLine(new ListLine().addValue(0, true)); 22 | handler.flush(); 23 | 24 | } 25 | @Test 26 | public void testA() { 27 | String i=null; 28 | try { 29 | i.equals("a"); 30 | } catch (Exception e) { 31 | throw new RuntimeException("test for me"); 32 | }finally { 33 | System.out.println(123); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/DoubleFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import org.apache.commons.lang3.StringUtils; 6 | 7 | import com.bing.excel.converter.AbstractFieldConvertor; 8 | import com.bing.excel.core.handler.ConverterHandler; 9 | import com.bing.excel.vo.OutValue; 10 | 11 | public final class DoubleFieldConverter extends AbstractFieldConvertor { 12 | 13 | @Override 14 | public boolean canConvert(Class type) { 15 | return type.equals(double.class) || type.equals(Double.class); 16 | } 17 | 18 | @Override 19 | public Object fromString(String cell,ConverterHandler converterHandler,Type targetType) { 20 | if(StringUtils.isBlank(cell)){ 21 | return null; 22 | } 23 | return Double.valueOf( cell); 24 | } 25 | 26 | @Override 27 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 28 | if(source==null){ 29 | return null; 30 | } 31 | return OutValue.doubleValue(source); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/exception/IllegalEntityException.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.exception; 2 | 3 | /** 4 | * 当用户定义model不符合需要时候抛出异常 5 | * @author shizhongtao 6 | * @time 7 | */ 8 | public class IllegalEntityException extends RuntimeException { 9 | @Override 10 | public String getMessage() { 11 | return super.getMessage(); 12 | } 13 | 14 | @Override 15 | public String toString() { 16 | return super.toString(); 17 | } 18 | 19 | public IllegalEntityException(Class clz,String message) { 20 | super("The model entity ["+clz.getName()+"]:"+message); 21 | 22 | } 23 | 24 | public IllegalEntityException(String message, Throwable cause) { 25 | super(message, cause); 26 | } 27 | public IllegalEntityException(Class clazz,String message, Throwable cause) { 28 | super("The model entity ["+clazz.getName()+"]:"+message,cause); 29 | } 30 | 31 | public IllegalEntityException(String message) { 32 | super(message); 33 | } 34 | 35 | public IllegalEntityException(Throwable cause) { 36 | super(cause); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/FloatFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.vo.OutValue; 8 | import com.google.common.base.Strings; 9 | 10 | /** 11 | * @author shizhongtao 12 | * 13 | * date 2016-3-21 14 | * Description: 15 | */ 16 | public final class FloatFieldConverter extends AbstractFieldConvertor { 17 | 18 | @Override 19 | public boolean canConvert(Class clz) { 20 | return clz.equals(float.class) || clz.equals(Float.class); 21 | } 22 | 23 | @Override 24 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 25 | if(Strings.isNullOrEmpty(cell)){ 26 | return null; 27 | } 28 | return Float.valueOf(cell); 29 | } 30 | 31 | @Override 32 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 33 | if(source==null){ 34 | return null; 35 | } 36 | return OutValue.dateValue(((Float)source).doubleValue()); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/annotation/BingConvertor.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import com.bing.excel.converter.FieldValueConverter; 10 | 11 | /** 12 | * 创建时间:2015-12-14下午2:11:27 项目名称:excel 13 | * 14 | * @author shizhongtao 15 | * @version 1.0 16 | * @since JDK 1.7 文件名称:BingConvertor.java 类说明: 17 | */ 18 | @Target(ElementType.FIELD) 19 | @Retention(RetentionPolicy.RUNTIME) 20 | @Documented 21 | public @interface BingConvertor { 22 | Class value() ; 23 | 24 | 25 | Class[] types() default {}; 26 | 27 | String[] strings() default {}; 28 | 29 | byte[] bytes() default {}; 30 | 31 | 32 | char[] chars() default {}; 33 | 34 | short[] shorts() default {}; 35 | 36 | int[] ints() default {}; 37 | 38 | long[] longs() default {}; 39 | 40 | float[] floats() default {}; 41 | 42 | double[] doubles() default {}; 43 | 44 | boolean[] booleans() default {}; 45 | } 46 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/LongFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.vo.OutValue; 8 | import com.google.common.base.Strings; 9 | 10 | public final class LongFieldConverter extends AbstractFieldConvertor { 11 | 12 | @Override 13 | public boolean canConvert(Class clz) { 14 | return clz.equals(long.class) || clz.equals(Long.class); 15 | } 16 | 17 | @Override 18 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 19 | if (Strings.isNullOrEmpty(cell)) { 20 | return null; 21 | } 22 | char c1 = cell.charAt(1); 23 | if (c1 == 'x' || c1 == 'X') { 24 | return Long.decode(cell); 25 | } 26 | return Long.parseLong(cell); 27 | } 28 | 29 | @Override 30 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 31 | if(source==null){ 32 | return null; 33 | } 34 | return OutValue.longValue(source); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/writer/DefaultFileWriteHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.writer; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.OutputStream; 8 | 9 | import org.apache.poi.ss.usermodel.Workbook; 10 | 11 | import com.bing.excel.writer.exception.ExcelOutException; 12 | 13 | /** 14 | * 不是线程安全的 15 | * @author shizhongtao 16 | * 17 | */ 18 | public class DefaultFileWriteHandler extends AbstractWriteHandler { 19 | 20 | private transient OutputStream os; 21 | 22 | 23 | 24 | DefaultFileWriteHandler(Workbook wb, File file) 25 | throws FileNotFoundException { 26 | super(wb,new FileOutputStream(file)); 27 | this.os=super.os; 28 | } 29 | 30 | DefaultFileWriteHandler(Workbook wb, String path) { 31 | super(wb, path); 32 | this.os=super.os; 33 | } 34 | 35 | 36 | 37 | 38 | @Override 39 | public void flush() { 40 | try { 41 | if (os != null) { 42 | super.flush(); 43 | this.os.close(); 44 | } 45 | } catch (IOException e) { 46 | throw new ExcelOutException("Happen exception when flush", e); 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/CharacterFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.vo.OutValue; 8 | 9 | /** 10 | * @author shizhongtao 11 | * 12 | * date 2016-3-21 13 | * Description: 14 | */ 15 | public final class CharacterFieldConverter extends AbstractFieldConvertor { 16 | 17 | @Override 18 | public boolean canConvert(Class clz) { 19 | return clz.equals(char.class) || clz.equals(Character.class); 20 | } 21 | 22 | @Override 23 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 24 | if (cell==null) { 25 | return null; 26 | } 27 | if (cell.length() == 0) { 28 | return new Character('\0'); 29 | } else { 30 | return new Character(cell.charAt(0)); 31 | } 32 | } 33 | 34 | @Override 35 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 36 | if (source==null) { 37 | return null; 38 | } 39 | return OutValue.stringValue(source.toString()); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/writer/DefaultStreamWriteHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.writer; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.IOException; 5 | import java.io.OutputStream; 6 | 7 | import org.apache.poi.ss.usermodel.Workbook; 8 | 9 | import com.bing.excel.writer.exception.ExcelOutException; 10 | 11 | /** 12 | * 不是线程安全的 13 | * @author shizhongtao 14 | * 15 | */ 16 | public class DefaultStreamWriteHandler extends AbstractWriteHandler { 17 | private transient OutputStream os; 18 | 19 | /** 20 | * @param wb 21 | * @param outStream 22 | * U should close the stream by youself. 23 | * @throws FileNotFoundException 24 | */ 25 | DefaultStreamWriteHandler(Workbook wb, OutputStream outStream) { 26 | super(wb, outStream); 27 | this.os = super.os; 28 | 29 | } 30 | 31 | 32 | 33 | /* 34 | * (non-Javadoc) 35 | * 36 | * @see com.chinamobile.excel.writer.WriterHandler#flush() 37 | */ 38 | @Override 39 | public void flush() { 40 | try { 41 | if (os != null) { 42 | this.os.flush(); 43 | super.flush(); 44 | } 45 | } catch (IOException e) { 46 | 47 | throw new ExcelOutException("Happen exception when flush", e); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/annotation/CellConfig.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.annotation; 2 | 3 | import java.lang.annotation.Documented; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | 10 | /** 11 | * 创建时间:2015-12-8下午9:41:18 项目名称:excel 12 | * 13 | * @author shizhongtao 14 | * @version 1.0 15 | * @since JDK 1.7 文件名称:BingCell.java 类说明: 16 | */ 17 | @Target(ElementType.FIELD) 18 | @Retention(RetentionPolicy.RUNTIME) 19 | @Documented 20 | public @interface CellConfig { 21 | /** 22 | *

Title: 下标值

23 | *

Description: 从0开始,转入时候必须有值,转出时用index值确定在excel中列数,如果没有则不能确定位置。

24 | * @return 转换为orm模型中java的类,如果不能转换返回null,基本类型中为默认值。 25 | */ 26 | public int index() ; 27 | 28 | /** 29 | * excel 读取数据时候,是不是为必须参数。默认是false 30 | * @return true or false 31 | */ 32 | public boolean readRequired() default false; 33 | /** 34 | * excel导出时候,字段是否忽略导出,default false。 35 | * @return ture or false 36 | */ 37 | //public boolean omitOutput() default false; 38 | 39 | /** 40 | * 输出时候的title名称 41 | * @return 别名 42 | */ 43 | public String aliasName() default ""; 44 | } 45 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/vo/OutValue.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.vo; 2 | 3 | public class OutValue { 4 | public enum OutType { 5 | INTEGER, LONG, DOUBLE, STRING, DATE, UNDEFINED 6 | } 7 | 8 | private OutType outType; 9 | private Object value; 10 | 11 | 12 | 13 | public OutValue(OutType outType, Object value) { 14 | super(); 15 | this.outType = outType; 16 | this.value = value; 17 | } 18 | public static OutValue intValue(Object obj){ 19 | return new OutValue(OutType.INTEGER,obj); 20 | } 21 | public static OutValue doubleValue(Object obj){ 22 | return new OutValue(OutType.DOUBLE,obj); 23 | } 24 | public static OutValue longValue(Object obj){ 25 | return new OutValue(OutType.LONG,obj); 26 | } 27 | public static OutValue stringValue(Object obj){ 28 | return new OutValue(OutType.STRING,obj); 29 | } 30 | public static OutValue dateValue(Object obj){ 31 | return new OutValue(OutType.DATE,obj); 32 | } 33 | public OutType getOutType() { 34 | return outType; 35 | } 36 | public void setOutType(OutType outType) { 37 | this.outType = outType; 38 | } 39 | public Object getValue() { 40 | return value; 41 | } 42 | public void setValue(Object value) { 43 | this.value = value; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/ShortFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.vo.OutValue; 8 | import com.google.common.base.Strings; 9 | 10 | public final class ShortFieldConverter extends AbstractFieldConvertor { 11 | 12 | @Override 13 | public boolean canConvert(Class clz) { 14 | return clz.equals(short.class) || clz.equals(Short.class); 15 | } 16 | 17 | @Override 18 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 19 | if(Strings.isNullOrEmpty(cell)){ 20 | return null; 21 | } 22 | int value = Integer.valueOf(cell).intValue(); 23 | if(value < Short.MIN_VALUE || value > Short.MAX_VALUE) { 24 | throw new NumberFormatException("For input string: \"" + cell + '"'); 25 | } 26 | return new Short((short)value); 27 | } 28 | 29 | @Override 30 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 31 | if(source==null){ 32 | return null; 33 | } 34 | return OutValue.intValue(((Short)source).intValue()); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/enums/EnumConVerter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.enums; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.converter.AbstractFieldConvertor; 6 | import com.bing.excel.core.handler.ConverterHandler; 7 | 8 | /** 9 | * @author shizhongtao 10 | * 11 | * date 2016-3-21 12 | * Description: 13 | */ 14 | public class EnumConVerter extends AbstractFieldConvertor { 15 | 16 | @Override 17 | public boolean canConvert(Class clz) { 18 | return clz.isEnum() || Enum.class.isAssignableFrom(clz); 19 | } 20 | 21 | 22 | 23 | @Override 24 | public Object fromString(String cell,ConverterHandler converterHandler,Type type) { 25 | if(type==null){ 26 | return null; 27 | } 28 | Class targetType=(Class) type; 29 | if (targetType.getSuperclass() != Enum.class) { 30 | targetType = targetType.getSuperclass(); // polymorphic enums 31 | } 32 | try { 33 | return Enum.valueOf(targetType, cell); 34 | } catch (IllegalArgumentException e) { 35 | Enum[] enumConstants = (Enum[])targetType.getEnumConstants(); 36 | for (Enum item : enumConstants) { 37 | if(item.name().equals(cell)){ 38 | return item; 39 | } 40 | } 41 | 42 | throw e; 43 | } 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/ByteFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.vo.OutValue; 8 | import com.google.common.base.Strings; 9 | 10 | /** 11 | * @author shizhongtao 12 | * 13 | * date 2016-3-21 14 | * Description: 15 | */ 16 | public final class ByteFieldConverter extends AbstractFieldConvertor { 17 | 18 | @Override 19 | public boolean canConvert(Class clz) { 20 | return clz.equals(byte.class) || clz.equals(Byte.class); 21 | } 22 | 23 | 24 | 25 | @Override 26 | public Object fromString(String cell, ConverterHandler converterHandler, Type targetType) { 27 | if (Strings.isNullOrEmpty(cell)) { 28 | return null; 29 | } 30 | int value = Integer.decode(cell).intValue(); 31 | if(value < Byte.MIN_VALUE || value > 0xFF) { 32 | throw new NumberFormatException("For input string: \"" + cell + '"'); 33 | } 34 | return new Byte((byte)value); 35 | } 36 | 37 | 38 | 39 | @Override 40 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 41 | if (source==null) { 42 | return null; 43 | } 44 | return OutValue.intValue(((Byte)source).intValue()); 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/ReadHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader; 2 | 3 | import java.io.IOException; 4 | 5 | import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 6 | import org.xml.sax.SAXException; 7 | 8 | /** 9 | * @author shizhongtao 10 | * 11 | * date 2016-3-1 12 | * Description: 13 | */ 14 | public interface ReadHandler { 15 | /** 16 | * 处理所用数据对象 17 | * @throws IOException 18 | * @throws OpenXML4JException 19 | * @throws SAXException 20 | */ 21 | void readSheets() throws IOException, OpenXML4JException , SAXException; 22 | void readSheets(int maxReadLine) throws IOException, OpenXML4JException , SAXException; 23 | /** 24 | * 读取指定的数据 25 | * @param index sheetDate对应下标 0 start 26 | * @throws IOException 27 | * @throws OpenXML4JException 28 | * @throws SAXException 29 | */ 30 | void readSheet(int index)throws IOException, OpenXML4JException , SAXException; 31 | void readSheet(int[] indexs)throws IOException, OpenXML4JException , SAXException; 32 | void readSheet(String indexName)throws IOException, OpenXML4JException , SAXException; 33 | void readSheet(int index,int maxReadLine)throws IOException, OpenXML4JException , SAXException; 34 | void readSheet(int[] indexs,int maxReadLine)throws IOException, OpenXML4JException , SAXException; 35 | void readSheet(String indexName,int maxReadLine)throws IOException, OpenXML4JException , SAXException; 36 | } 37 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/writer/SXSSFWriterHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.writer; 2 | 3 | import java.io.IOException; 4 | import java.io.OutputStream; 5 | 6 | import org.apache.poi.ss.usermodel.Workbook; 7 | import org.apache.poi.xssf.streaming.SXSSFSheet; 8 | import org.apache.poi.xssf.streaming.SXSSFWorkbook; 9 | 10 | import com.bing.excel.writer.exception.ExcelOutException; 11 | 12 | public class SXSSFWriterHandler extends AbstractWriteHandler { 13 | private transient OutputStream os; 14 | private SXSSFWorkbook wb; 15 | public SXSSFWriterHandler(Workbook wb, OutputStream outStream) { 16 | super(wb, outStream); 17 | this.os=super.os; 18 | this.wb=(SXSSFWorkbook) wb; 19 | } 20 | 21 | public SXSSFWriterHandler(Workbook wb, String path) { 22 | super(wb, path); 23 | this.os=super.os; 24 | this.wb=(SXSSFWorkbook) wb; 25 | } 26 | 27 | @ Override 28 | public void flush() { 29 | try { 30 | if (os != null) { 31 | super.flush(); 32 | this.os.close(); 33 | this.wb.dispose(); 34 | } 35 | } catch (IOException e) { 36 | throw new ExcelOutException("Happen exception when flush", e); 37 | } 38 | } 39 | 40 | public void setCurrentSheetByName(String name, int lineNum){ 41 | SXSSFSheet sheet = wb.getSheet(name); 42 | if(sheet==null){ 43 | throw new NullPointerException(String.format("no sheet named [%s]", name)); 44 | }else{ 45 | super.currentSheet=sheet; 46 | super.currentRowIndex=lineNum; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/IntegerFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.converter.AbstractFieldConvertor; 6 | import com.bing.excel.core.handler.ConverterHandler; 7 | import com.bing.excel.vo.OutValue; 8 | import com.bing.excel.vo.OutValue.OutType; 9 | import com.google.common.base.Strings; 10 | 11 | /** 12 | * @author shizhongtao 13 | * 14 | * date 2016-3-10 Description: 15 | */ 16 | public final class IntegerFieldConverter extends AbstractFieldConvertor { 17 | 18 | @Override 19 | public boolean canConvert(Class clz) { 20 | return clz.equals(int.class) || clz.equals(Integer.class); 21 | } 22 | 23 | /** 24 | * @return return the long value; return Long.decode(str),only in this case the str start with "0x" 25 | */ 26 | @Override 27 | public Object fromString(String cell,ConverterHandler converterHandler,Type targetType) { 28 | 29 | if (Strings.isNullOrEmpty(cell)) { 30 | return null; 31 | } 32 | long value= Long.decode(cell).longValue(); 33 | if(value < Integer.MIN_VALUE || value > 0xFFFFFFFFl) { 34 | throw new NumberFormatException("For input string: \"" + cell + '"'); 35 | } 36 | return new Integer((int)value); 37 | } 38 | 39 | @Override 40 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 41 | if(source==null){ 42 | return null; 43 | } 44 | return OutValue.intValue(source); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/BingExcelEvent.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | import com.bing.excel.core.rw.BingWriterHandler; 4 | 5 | import java.io.File; 6 | import java.io.FileNotFoundException; 7 | import java.io.InputStream; 8 | 9 | 10 | /** 11 | * @author shizhongtao 12 | * 13 | */ 14 | @Deprecated 15 | public interface BingExcelEvent { 16 | 17 | 18 | void readFile(File file, Class clazz, int startRowNum,BingReadListener listener) throws Exception ; 19 | /** 20 | * 根据condition条件读取相应的sheet到list对象 21 | * @param file 22 | * @param condition 23 | * @param listener 24 | * @return 25 | */ 26 | void readFile(File file, ReaderCondition condition,BingReadListener listener) throws Exception ; 27 | 28 | 29 | /** 30 | * 读取所有sheet表格,到list 31 | * @param file 32 | * @param conditions 每个表格对应的condition 33 | * @return 34 | */ 35 | void readFileToList(File file,ReaderCondition[] conditions,BingReadListener listener) throws Exception; 36 | 37 | 38 | 39 | /** 40 | * 读取第一个sheet到SheetVo 41 | * @param stream 42 | * @param condition 43 | * @return 44 | */ 45 | void readStream(InputStream stream,ReaderCondition condition,BingReadListener listener) throws Exception; 46 | void readStream(InputStream stream,Class clazz, int startRowNum,BingReadListener listener) throws Exception; 47 | 48 | void readStreamToList(InputStream stream, ReaderCondition[] condition,BingReadListener listener) throws Exception; 49 | 50 | 51 | BingWriterHandler writeFile(File file)throws FileNotFoundException; 52 | 53 | BingWriterHandler writeFile(String path); 54 | // BingWriterHandler writeFile(OutputStream stream); 55 | } 56 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/common/FieldRelation.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core.common; 2 | 3 | 4 | public final class FieldRelation { 5 | private final String name; 6 | private final String declaringClass; 7 | 8 | public FieldRelation(String definedIn, String name) { 9 | this.name = name; 10 | this.declaringClass = definedIn; 11 | } 12 | 13 | public FieldRelation(Class definedIn, String name) { 14 | this(definedIn == null ? null : definedIn.getName(), name); 15 | } 16 | 17 | public String getName() { 18 | return this.name; 19 | } 20 | 21 | public String getDeclaringClass() { 22 | return this.declaringClass; 23 | } 24 | 25 | public boolean equals(Object obj) { 26 | if (this == obj) { 27 | return true; 28 | } 29 | if (obj == null) { 30 | return false; 31 | } 32 | if (obj instanceof FieldRelation) { 33 | final FieldRelation field = (FieldRelation)obj; 34 | if ((declaringClass == null && field.declaringClass != null) 35 | || (declaringClass != null && field.declaringClass == null)) { 36 | return false; 37 | } 38 | return name.equals(field.getName()) 39 | && (declaringClass == null || declaringClass.equals(field.getDeclaringClass())); 40 | } 41 | return false; 42 | } 43 | 44 | public int hashCode() { 45 | return name.hashCode() ^ (declaringClass == null ? 0 : declaringClass.hashCode()); 46 | } 47 | 48 | public String toString() { 49 | return (declaringClass == null ? "" : declaringClass + ".") + name; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/ReaderCondition.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | 4 | /** 5 | * 读取条件类 6 | * @author shizhongtao 7 | * 8 | * date 2016-2-17 Description: 9 | */ 10 | public class ReaderCondition { 11 | private int startRow = 1; 12 | private int endRow = Integer.MAX_VALUE; 13 | private int sheetIndex = 0; 14 | private Class clazz; 15 | 16 | /** 17 | * @param sheetIndex index of sheet,started 0; 18 | * @param clazz 19 | */ 20 | public ReaderCondition(int sheetIndex, Class clazz) { 21 | this.sheetIndex = sheetIndex; 22 | this.clazz = clazz; 23 | } 24 | 25 | 26 | 27 | /** 28 | * @param sheetIndex 29 | * @param startRow from which line to read.started 0;default 1; 30 | * @param clazz 31 | */ 32 | public ReaderCondition(int sheetIndex, int startRow, Class clazz) { 33 | this.startRow = startRow; 34 | this.sheetIndex = sheetIndex; 35 | this.clazz = clazz; 36 | } 37 | 38 | public ReaderCondition setStartRow(int startRow) { 39 | this.startRow = startRow; 40 | return this; 41 | } 42 | 43 | /** 44 | * @param endRow the end index num of row ,0 started。default Integer.MAX_VALUE 45 | * @return 46 | */ 47 | public ReaderCondition setEndRow(int endRow) { 48 | this.endRow = endRow; 49 | return this; 50 | } 51 | 52 | public ReaderCondition setSheetIndex(int sheetIndex) { 53 | this.sheetIndex = sheetIndex; 54 | return this; 55 | } 56 | 57 | public int getStartRow() { 58 | return startRow; 59 | } 60 | 61 | public int getEndRow() { 62 | return endRow; 63 | } 64 | 65 | public int getSheetIndex() { 66 | return sheetIndex; 67 | } 68 | 69 | public Class getTargetClazz() { 70 | return clazz; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/SaxReaderTest1.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | 5 | import org.junit.Test; 6 | 7 | import com.bing.excel.reader.ExcelReadListener; 8 | import com.bing.excel.reader.ExcelReaderFactory; 9 | import com.bing.excel.reader.ReadHandler; 10 | import com.bing.excel.vo.ListRow; 11 | 12 | /** 13 | * @author shizhongtao 14 | * 15 | * date 2016-3-23 16 | * Description: 17 | */ 18 | public class SaxReaderTest1 { 19 | //如果以上都不能满足你的需求 你也可以自己去处理数据。 20 | @Test 21 | public void testme() throws Exception{ 22 | //InputStream stream = Salary.class.getResourceAsStream("/salary6.xls"); 23 | //File f = new File("E:/aoptest/gzb.xls"); 24 | //File f = new File("E:/aoptest/bc.xlsx"); 25 | File f = new File("E:/aoptest/b.xlsx"); 26 | // 27 | System.out.println(System.currentTimeMillis()); 28 | ReadHandler saxHandler = ExcelReaderFactory.create(f, new ExcelReadListener() { 29 | 30 | @Override 31 | public void startSheet(int sheetIndex, String name) { 32 | // TODO Auto-generated method stub 33 | System.out.println(System.currentTimeMillis()); 34 | } 35 | 36 | @Override 37 | public void optRow(int curRow, ListRow rowList) { 38 | //输出读取的数据列表。这里数据全部是string类型 39 | System.out.println(rowList); 40 | } 41 | 42 | @Override 43 | public void endWorkBook() { 44 | // TODO Auto-generated method stub 45 | System.out.println(System.currentTimeMillis()); 46 | } 47 | 48 | @Override 49 | public void endSheet(int sheetIndex, String name) { 50 | // TODO Auto-generated method stub 51 | 52 | } 53 | }, true); 54 | saxHandler.readSheets(); 55 | System.out.println(System.currentTimeMillis()); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/CSVTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import com.bing.excel.core.BingExcel; 4 | import com.bing.excel.core.BingExcelBuilder; 5 | import com.bing.utils.FileCreateUtils; 6 | 7 | import com.chinamobile.excel.WriteTest2; 8 | import org.apache.commons.csv.CSVFormat; 9 | import org.apache.commons.csv.CSVPrinter; 10 | import org.junit.Test; 11 | 12 | import java.io.FileWriter; 13 | import java.io.IOException; 14 | import java.io.Writer; 15 | import java.util.ArrayList; 16 | import java.util.List; 17 | 18 | /** 19 | * Created by szt on 2016/11/24. 20 | */ 21 | public class CSVTest { 22 | @Test 23 | public void csvWrite() throws IOException { 24 | Writer out = new FileWriter(FileCreateUtils.createFile("/Users/shi/workspace/a.csv")); 25 | out.write(new String(new byte[] { (byte) 0xEF, (byte) 0xBB,(byte) 0xBF })); 26 | 27 | final String[] FILE_HEADER = {"ID", "我", "Gender", "Major"}; 28 | CSVFormat format = CSVFormat.DEFAULT.withHeader(FILE_HEADER); 29 | CSVPrinter csvPrinter = new CSVPrinter(out, format); 30 | csvPrinter.printRecord(12, "乱码", null, "gis"); 31 | csvPrinter.close(); 32 | } 33 | 34 | 35 | @Test 36 | public void terst() { 37 | List list=new ArrayList<>(); 38 | list.add("sadf"); 39 | list.add(0,"sdf"); 40 | // list.add(1,"adf"); 41 | // list.add(3,"asdf"); 42 | System.out.println(list.size()); 43 | } 44 | 45 | 46 | @Test 47 | public void tersWrite() throws IOException { 48 | BingExcel excel= BingExcelBuilder.builderInstance(); 49 | List ps = new ArrayList<>(); 50 | ps.add(new WriteTest2 51 | .Person(23,"he",3.45)); 52 | ps.add(new WriteTest2 53 | .Person(213,"你好",3.45)); 54 | 55 | excel.writeCSV("/Users/shi/workspace/ab.csv",ps); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/UserDefineMapperHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | 5 | /** 6 | * @author shizhongtao 7 | * @version 1.0 8 | * @date 2018-2-22 9 | * @since JDK 1.8 文件名称:UserDefineMapperHandler.java 类说明: 10 | */ 11 | public class UserDefineMapperHandler implements ExcelConverterMapperHandler { 12 | 13 | 14 | private ConversionMapper objConversionMapper; 15 | 16 | 17 | public UserDefineMapperHandler(ConversionMapper conversionMapper) { 18 | 19 | this.objConversionMapper = conversionMapper; 20 | } 21 | 22 | public UserDefineMapperHandler(ConversionMapperBuilder conversionMapperBuilder) { 23 | 24 | this.objConversionMapper = conversionMapperBuilder.build(); 25 | if (this.objConversionMapper == null) { 26 | throw new NullPointerException("objConversionMapper is null"); 27 | 28 | } 29 | } 30 | 31 | @Override 32 | public ConversionMapper getObjConversionMapper() { 33 | return objConversionMapper; 34 | } 35 | 36 | /* 37 | * (non-Javadoc) 38 | * 39 | * @see com.chinamobile.excel.mapper.OrmMapper#getLocalConverter(java.lang.Class, 40 | * java.lang.String) 41 | */ 42 | 43 | @Override 44 | public FieldValueConverter getLocalConverter(Class definedIn, 45 | String fieldName) { 46 | 47 | return objConversionMapper.getLocalConverter(definedIn, fieldName); 48 | } 49 | 50 | @Override 51 | public ConversionMapper.FieldConverterMapper getLocalFieldConverterMapper(Class definedIn, 52 | String fieldName) { 53 | 54 | return objConversionMapper.getLocalConverterMapper(definedIn, fieldName); 55 | } 56 | 57 | 58 | @Override 59 | public String getModelName(Class key) { 60 | return objConversionMapper.getAliasName(key); 61 | } 62 | 63 | 64 | } 65 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/vo/CellKV.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.vo; 2 | 3 | import javax.management.RuntimeOperationsException; 4 | 5 | import com.google.common.base.MoreObjects; 6 | 7 | /** 8 | * @author shizhongtao 9 | * 10 | * date 2016-3-1 11 | * Description: 12 | */ 13 | public class CellKV { 14 | 15 | /** 16 | * @serial Attribute name. 17 | */ 18 | private int index; 19 | 20 | /** 21 | * @serial Attribute value 22 | */ 23 | private T value = null; 24 | 25 | /** 26 | * Constructs an CellKV object which associates the given attribute name 27 | * with the given value. 28 | * 29 | * @param index 30 | * A Int of the index cell,0 started. 31 | * @param value 32 | * The Object which is assigned to the attribute. This object 33 | * must be of the same type as the attribute. 34 | * 35 | */ 36 | public CellKV(int index, T value) { 37 | 38 | if (index < 0) { 39 | throw new RuntimeOperationsException(new IllegalArgumentException( 40 | "CellKV index cannot be ls 0 ")); 41 | } 42 | 43 | this.index = index; 44 | this.value = value; 45 | } 46 | 47 | /** 48 | * Returns a String containing the name of the attribute. 49 | * 50 | * @return the name of the attribute. 51 | */ 52 | public int getIndex() { 53 | return index; 54 | } 55 | 56 | /** 57 | * Returns an String that is the value of this attribute. 58 | * 59 | * @return the value of the attribute. 60 | */ 61 | public T getValue() { 62 | return value; 63 | } 64 | 65 | /** 66 | * Returns a String object representing this Attribute's value. The format 67 | * of this string is not specified, but users can expect that two Attributes 68 | * return the same string if and only if they are equal. 69 | */ 70 | public String toString() { 71 | return MoreObjects.toStringHelper(this).omitNullValues() 72 | .add("index", index).add("value", value).toString(); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/handler/LocalConverterHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core.handler; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Collection; 5 | import java.util.Collections; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import com.bing.excel.converter.FieldValueConverter; 10 | import com.bing.excel.exception.ConversionException; 11 | import com.bing.excel.mapper.BaseGlobalConverterMapper; 12 | 13 | import com.google.common.primitives.Primitives; 14 | 15 | public class LocalConverterHandler implements ConverterHandler { 16 | private final Map, FieldValueConverter> defaultLocalConverter = Collections 17 | .synchronizedMap(new HashMap, FieldValueConverter>()); 18 | 19 | 20 | @Override 21 | public void registerConverter(Class clazz, 22 | FieldValueConverter converter) { 23 | if (converter.canConvert(clazz)) { 24 | 25 | if (clazz.isPrimitive()) { 26 | defaultLocalConverter.put(Primitives.wrap(clazz), converter); 27 | } else { 28 | defaultLocalConverter.put(clazz, converter); 29 | } 30 | } else { 31 | throw new ConversionException("register converter for[" 32 | + clazz.getName() + "] failed!"); 33 | } 34 | } 35 | 36 | 37 | @Override 38 | public FieldValueConverter getLocalConverter(Class keyFieldType) { 39 | FieldValueConverter fieldValueConverter = defaultLocalConverter.get(keyFieldType); 40 | if(fieldValueConverter==null){ 41 | final Class keyType; 42 | if (keyFieldType.isEnum() || Enum.class.isAssignableFrom(keyFieldType)) { 43 | keyType=Enum.class; 44 | } else if(keyFieldType.isArray()){ 45 | keyType=Array.class; 46 | }else if(Collection.class.isAssignableFrom(keyFieldType)){ 47 | keyType=Collection.class; 48 | }else{ 49 | keyType=keyFieldType; 50 | } 51 | fieldValueConverter= BaseGlobalConverterMapper.globalFieldConverterMapper.get(keyType); 52 | if (fieldValueConverter!=null) { 53 | defaultLocalConverter.put(keyFieldType, fieldValueConverter); 54 | } 55 | } 56 | return fieldValueConverter; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/AnotationTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | 4 | import java.lang.reflect.Field; 5 | import java.lang.reflect.ParameterizedType; 6 | import java.lang.reflect.Type; 7 | import java.util.ArrayList; 8 | import java.util.Collection; 9 | import java.util.HashSet; 10 | import java.util.LinkedList; 11 | import java.util.List; 12 | import java.util.Set; 13 | 14 | import org.junit.Test; 15 | 16 | import com.bing.excel.annotation.OutAlias; 17 | 18 | import com.google.common.collect.Lists; 19 | import com.google.common.collect.Sets; 20 | 21 | public class AnotationTest { 22 | 23 | @Test 24 | public void testOut() throws IllegalAccessException{ 25 | Field[] fields = Person.class.getDeclaredFields(); 26 | for (Field field : fields) { 27 | System.out.println(getFieldClass(field)); 28 | System.out.println("____________"); 29 | //System.out.println(createCollection(field.getType())); 30 | } 31 | 32 | } 33 | 34 | 35 | 36 | private static Class getFieldClass(Field field) { 37 | Class fieldClazz = field.getType(); 38 | 39 | if (Collection.class.isAssignableFrom(fieldClazz)) { 40 | Type fc = field.getGenericType(); // 关键的地方,如果是List类型,得到其Generic的类型 41 | System.out.println(fc); 42 | 43 | if (fc instanceof ParameterizedType) // 如果是泛型参数的类型 44 | { 45 | ParameterizedType pt = (ParameterizedType) fc; 46 | 47 | fieldClazz = (Class) pt.getActualTypeArguments()[0]; //得到泛型里的class类型对象。 48 | } 49 | } 50 | 51 | return fieldClazz; 52 | } 53 | private Collection createCollection(Class type) { 54 | if (type == null) { 55 | return null; 56 | } 57 | if(type.equals(ArrayList.class)||type.equals(List.class)){ 58 | return Lists.newArrayList(); 59 | }else if(type.equals(HashSet.class)||type.equals(Set.class)){ 60 | return Sets.newHashSet(); 61 | }else if(type.equals(LinkedList.class)){ 62 | return Lists.newArrayList(); 63 | }else{ 64 | return null; 65 | } 66 | 67 | } 68 | } 69 | @OutAlias("nihao") 70 | class Person{ 71 | private String name; 72 | private Integer age; 73 | private List li; 74 | private HashSet set; 75 | private ArrayList al; 76 | } 77 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/ConversionMapperBuilder.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | import javafx.util.Builder; 5 | 6 | /** 7 | * ConversionMapperBuildder 用于 8 | * 9 | * @author shi 10 | * @create 2018-02-22. 11 | */ 12 | public class ConversionMapperBuilder { 13 | 14 | private ConversionMapper conversionMapper = new ConversionMapper(); 15 | 16 | private ConversionMapperBuilder() { 17 | 18 | } 19 | 20 | public static ConversionMapperBuilder toBuilder() { 21 | return new ConversionMapperBuilder(); 22 | } 23 | 24 | public ConversionMapper build() { 25 | return this.conversionMapper; 26 | } 27 | 28 | public ConversionMapperBuilder modelName(Class clazz, String name) { 29 | this.conversionMapper.addModelName(clazz, name); 30 | return this; 31 | } 32 | 33 | public ConversionMapperBuilder fieldConverter(Class clazz, String filedName, 34 | Class filedType, int index) { 35 | this.fieldConverter(clazz, filedName, filedType, index, null, null, false); 36 | return this; 37 | } 38 | 39 | public ConversionMapperBuilder fieldConverter(Class clazz, String filedName, 40 | Class filedType, int index, 41 | FieldValueConverter converter) { 42 | this.fieldConverter(clazz, filedName, filedType, index, null, converter, false); 43 | return this; 44 | } 45 | 46 | public ConversionMapperBuilder fieldConverter(Class clazz, String filedName, 47 | Class filedType, int index, 48 | String alias) { 49 | this.fieldConverter(clazz, filedName, filedType, index, alias, null, false); 50 | return this; 51 | } 52 | 53 | public ConversionMapperBuilder fieldConverter(Class clazz, String filedName, 54 | Class filedType, int index, 55 | String alias, FieldValueConverter converter) { 56 | this.fieldConverter(clazz, filedName, filedType, index, alias, converter, false); 57 | return this; 58 | } 59 | 60 | public ConversionMapperBuilder fieldConverter(Class clazz, String filedName, 61 | Class filedType, int index, 62 | String alias, FieldValueConverter converter, boolean required) { 63 | if (alias == null) { 64 | alias = filedName; 65 | } 66 | 67 | this.conversionMapper 68 | .registerLocalConverter(clazz, filedName, index, alias, filedType, required, converter); 69 | return this; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/BaseGlobalConverterMapper.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.Collection; 5 | import java.util.Date; 6 | 7 | import com.bing.excel.converter.FieldValueConverter; 8 | import com.bing.excel.converter.base.ByteFieldConverter; 9 | import com.bing.excel.converter.base.DoubleFieldConverter; 10 | import com.bing.excel.converter.base.ShortFieldConverter; 11 | import com.bing.excel.converter.collections.CollectionConverter; 12 | import com.bing.excel.converter.enums.EnumConVerter; 13 | import com.bing.excel.converter.base.BooleanFieldConverter; 14 | import com.bing.excel.converter.base.CharacterFieldConverter; 15 | import com.bing.excel.converter.base.DateFieldConverter; 16 | import com.bing.excel.converter.base.FloatFieldConverter; 17 | import com.bing.excel.converter.base.IntegerFieldConverter; 18 | import com.bing.excel.converter.base.LongFieldConverter; 19 | import com.bing.excel.converter.base.StringFieldConverter; 20 | import com.bing.excel.converter.collections.ArrayConverter; 21 | 22 | import com.google.common.collect.ImmutableMap; 23 | 24 | /** 25 | * 默认的全局转换类,先静态吧,容我想想 26 | * 27 | * @author shizhongtao 28 | * 29 | * date 2016-3-19 30 | * Description: 31 | */ 32 | public class BaseGlobalConverterMapper { 33 | 34 | static ImmutableMap.Builder, FieldValueConverter> builder; 35 | 36 | static { 37 | builder = ImmutableMap.builder(); 38 | builder.put(String.class, new StringFieldConverter()); 39 | builder.put(Date.class, new DateFieldConverter()); 40 | builder.put(Enum.class, new EnumConVerter()); 41 | // builder.put(Array.class, new ArrayConverter()); 42 | //builder.put(Collections.class,new ArrayConverter()); 43 | 44 | builder.put(Integer.class, new IntegerFieldConverter()); 45 | builder.put(Long.class, new LongFieldConverter()); 46 | builder.put(Boolean.class, new BooleanFieldConverter()); 47 | builder.put(Byte.class, new ByteFieldConverter()); 48 | builder.put(Character.class, new CharacterFieldConverter()); 49 | builder.put(Double.class, new DoubleFieldConverter()); 50 | builder.put(Float.class, new FloatFieldConverter()); 51 | builder.put(Short.class, new ShortFieldConverter()); 52 | // builder.put(Collection.class, new CollectionConverter()); 53 | } 54 | 55 | public final static ImmutableMap, FieldValueConverter> globalFieldConverterMapper = builder 56 | .build(); 57 | 58 | } 59 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/utils/FileCreateUtils.java: -------------------------------------------------------------------------------- 1 | package com.bing.utils; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | /** 6 | * 文件的创建删除类 7 | * @author shizhongtao 8 | * 9 | */ 10 | public class FileCreateUtils { 11 | public static File createFolderPath(String path) { 12 | File file = new File(path); 13 | if (!file.exists()) { 14 | file.mkdirs(); 15 | } 16 | return file; 17 | } 18 | 19 | public static File createchildFolder(String parent, String childName) { 20 | File file = new File(createFolderPath(parent), childName); 21 | file.mkdir(); 22 | return file; 23 | } 24 | 25 | public static File createchildFolder(File parent, String childName) { 26 | File file = new File(parent, childName); 27 | file.mkdirs(); 28 | return file; 29 | } 30 | 31 | public static File createFile(String path) { 32 | File file = new File(path); 33 | File parent = file.getParentFile(); 34 | String fileName = file.getName(); 35 | if (parent == null) { 36 | 37 | try { 38 | file.createNewFile(); 39 | } catch (IOException e) { 40 | 41 | } 42 | return file; 43 | } 44 | return createFile(parent, fileName); 45 | 46 | } 47 | 48 | public static boolean isExists(String Path) { 49 | File file = new File(Path); 50 | 51 | return file.exists(); 52 | } 53 | 54 | public static boolean deleteFile(String fullPath) { 55 | File file = new File(fullPath); 56 | if (file.isFile()) { 57 | return file.delete(); 58 | } 59 | return false; 60 | } 61 | 62 | public static File createFile(String parent, String fileName) { 63 | File file = new File(parent); 64 | return createFile(file, fileName); 65 | } 66 | 67 | public static File createFile(File parent, String fileName) { 68 | 69 | File file = new File(parent, fileName); 70 | 71 | try { 72 | 73 | if (!parent.exists()) { 74 | parent.mkdirs(); 75 | } 76 | 77 | file.createNewFile(); 78 | } catch (IOException e) { 79 | 80 | return null; 81 | } 82 | return file; 83 | } 84 | 85 | public static boolean deleteDir(File dir) { 86 | if (dir.isDirectory()) { 87 | File[] children = dir.listFiles(); 88 | // 递归删除目录中的子目录下 89 | for (int i = 0; i < children.length; i++) { 90 | boolean success = deleteDir(children[i]); 91 | if (!success) { 92 | return false; 93 | } 94 | } 95 | } 96 | // 目录此时为空,可以删除 97 | return dir.delete(); 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/BooleanFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | 5 | import com.bing.excel.converter.AbstractFieldConvertor; 6 | import com.bing.excel.core.handler.ConverterHandler; 7 | import com.bing.excel.exception.ConversionException; 8 | import com.bing.excel.vo.OutValue; 9 | 10 | import com.google.common.base.Strings; 11 | 12 | /** 13 | * 14 | * @author shizhongtao 15 | * 16 | * date 2016-3-21 17 | * Description: thanks for Joe Walnes and David Blevins 18 | */ 19 | public final class BooleanFieldConverter extends AbstractFieldConvertor { 20 | private final boolean caseSensitive; 21 | private final String trueCaseStr; 22 | private final String falseCaseStr; 23 | 24 | /** 25 | * @param trueCaseStr 为真时候的输入 26 | * @param falseCaseStr 为家时候的输入 27 | * @param caseSensitive 是不是忽略大小写 28 | */ 29 | public BooleanFieldConverter(String trueCaseStr, String falseCaseStr, 30 | boolean caseSensitive) { 31 | this.caseSensitive = caseSensitive; 32 | this.trueCaseStr = trueCaseStr; 33 | this.falseCaseStr = falseCaseStr; 34 | } 35 | 36 | /** 37 | * 默认的boolean类型转换器,支持"TRUE", "FALSE"字符的转换 38 | */ 39 | public BooleanFieldConverter() { 40 | this("TRUE", "FALSE", false); 41 | } 42 | 43 | @Override 44 | public boolean canConvert(Class clz) { 45 | return clz.equals(boolean.class) || clz.equals(Boolean.class); 46 | } 47 | 48 | @Override 49 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 50 | if(source==null){ 51 | return null; 52 | } 53 | String re; 54 | if((boolean)source){ 55 | re=trueCaseStr; 56 | }else{ 57 | re=falseCaseStr; 58 | } 59 | return OutValue.stringValue(re); 60 | } 61 | 62 | /* 63 | * in other case ,return false?FIXME 64 | */ 65 | @Override 66 | public Object fromString(String cell,ConverterHandler converterHandler,Type targetType) { 67 | if (Strings.isNullOrEmpty(cell)) { 68 | return null; 69 | } 70 | Boolean re; 71 | if (caseSensitive) { 72 | re = trueCaseStr.equals(cell) ? Boolean.TRUE : Boolean.FALSE; 73 | } else { 74 | re = trueCaseStr.equalsIgnoreCase(cell) ? Boolean.TRUE 75 | : Boolean.FALSE; 76 | } 77 | if (!re) { 78 | if (caseSensitive) { 79 | if (!falseCaseStr.equals(cell)) { 80 | throw new ConversionException("Cann't parse value '"+cell+"' to java.lang.Boolean"); 81 | } 82 | } else { 83 | if (!falseCaseStr.equalsIgnoreCase(cell)) { 84 | 85 | } 86 | } 87 | } 88 | return re; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest3.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import org.apache.commons.lang3.RandomStringUtils; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import com.bing.excel.annotation.CellConfig; 8 | import com.bing.excel.annotation.OutAlias; 9 | import com.bing.excel.core.BingExcelEvent; 10 | import com.bing.excel.core.BingExcelEventBuilder; 11 | import com.bing.excel.core.rw.BingWriterHandler; 12 | 13 | import com.google.common.base.MoreObjects; 14 | 15 | /** 16 | * @author shizhongtao 17 | */ 18 | public class WriteTest3 { 19 | BingExcelEvent bing; 20 | 21 | @Before 22 | public void before() { 23 | bing = BingExcelEventBuilder.builderInstance(); 24 | } 25 | 26 | @Test 27 | public void testWrite() { 28 | /** 29 | * 对于数据量非常大时候,注意一点就是数据绝对不能放入到内存, 30 | * 你如果想初始化一个长多为百万级的list,劝你趁早放弃 31 | */ 32 | //测试百万级的写出, 33 | BingWriterHandler writerHandler = bing.writeFile("E:/aoptest/bigdata.xlsx"); 34 | // writerHandler.setMaxLine(100000); 35 | for (int i = 0; i < 1000000; i++) { 36 | writerHandler.writeLine(new Person(23, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 37 | } 38 | writerHandler.close(); 39 | } 40 | 41 | @OutAlias("xiaoshou") 42 | public static class Person { 43 | 44 | public Person(int age, String name, Double salary) { 45 | super(); 46 | this.age = age; 47 | this.name = name; 48 | this.salary = salary; 49 | } 50 | 51 | public Person() { 52 | super(); 53 | } 54 | 55 | @CellConfig(index = 1, aliasName = "年龄") 56 | private int age; 57 | @CellConfig(index = 0) 58 | private String name; 59 | @CellConfig(index = 3) 60 | private Double salary; 61 | private transient boolean testProperty = false; 62 | 63 | public String getName() { 64 | return name; 65 | } 66 | 67 | public void setName(String name) { 68 | this.name = name; 69 | } 70 | 71 | public int getAge() { 72 | return age; 73 | } 74 | 75 | public Double getSalary() { 76 | return salary; 77 | } 78 | 79 | public String toString() { 80 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 81 | .add("name", name).add("age", age).add("salary", salary) 82 | .toString(); 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTest4.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.net.URISyntaxException; 5 | import java.net.URL; 6 | import java.util.List; 7 | 8 | import org.junit.Test; 9 | 10 | import com.bing.excel.annotation.CellConfig; 11 | import com.bing.excel.core.BingExcel; 12 | import com.bing.excel.core.BingExcelBuilder; 13 | import com.bing.excel.core.ReaderCondition; 14 | import com.bing.excel.core.impl.BingExcelImpl.SheetVo; 15 | 16 | import com.google.common.base.MoreObjects; 17 | 18 | /** 19 | * @author shizhongtao 20 | * 21 | * date 2016-3-23 22 | * Description: 23 | */ 24 | public class ReadTest4 { 25 | 26 | @Test 27 | public void readExcelTest() throws URISyntaxException { 28 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 29 | URL url = Salary.class.getResource("/salary4.xlsx"); 30 | File f = new File(url.toURI()); 31 | 32 | BingExcel bing = BingExcelBuilder.toBuilder().builder(); 33 | try { 34 | ReaderCondition condition1=new ReaderCondition<>(0,1,Salary.class); 35 | ReaderCondition condition2=new ReaderCondition<>(1,1,Person.class); 36 | ReaderCondition[] arr=new ReaderCondition[]{condition1,condition2}; 37 | List list = bing.readFileToList(f, arr); 38 | for (SheetVo sheetVo : list) { 39 | System.out.println(sheetVo.getSheetIndex()+":"+sheetVo.getSheetName()); 40 | List list2 = sheetVo.getObjectList(); 41 | for (Object object : list2) { 42 | System.out.println(object); 43 | } 44 | } 45 | 46 | } catch (Exception e) { 47 | e.printStackTrace(); 48 | } 49 | 50 | } 51 | 52 | enum Department { 53 | develop, personnel, product; 54 | } 55 | public static class Salary { 56 | 57 | @CellConfig(index = 1) 58 | private String employNum; 59 | 60 | @CellConfig(index = 0) 61 | private String id; 62 | 63 | @CellConfig(index = 7) 64 | private Department department;// 枚举类型 65 | 66 | 67 | public String toString() { 68 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 69 | .add("id", id).add("employNum", employNum) 70 | .add("department", department) 71 | .toString(); 72 | } 73 | } 74 | 75 | public static class Person { 76 | @CellConfig(index = 0) 77 | private String id; 78 | @CellConfig(index = 2) 79 | private String name; 80 | @CellConfig(index = 1) 81 | private String num; 82 | 83 | public String toString() { 84 | return MoreObjects.toStringHelper(getClass()).add("name", name) 85 | .add("id", id).add("num", num).toString(); 86 | } 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest1.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.FileOutputStream; 4 | import java.io.IOException; 5 | import java.util.List; 6 | 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | import com.bing.excel.annotation.BingConvertor; 11 | import com.bing.excel.annotation.CellConfig; 12 | import com.bing.excel.annotation.OutAlias; 13 | import com.bing.excel.converter.base.BooleanFieldConverter; 14 | import com.bing.excel.core.BingExcel; 15 | import com.bing.excel.core.BingExcelBuilder; 16 | import com.google.common.base.MoreObjects; 17 | import com.google.common.collect.Lists; 18 | 19 | public class WriteTest1 { 20 | BingExcel bing; 21 | @Before 22 | public void before(){ 23 | bing = BingExcelBuilder.toBuilder().builder(); 24 | } 25 | @Test 26 | public void testWrite() throws IOException { 27 | List list = Lists.newArrayList(); 28 | list.add(new Person(12, "nihoa", 23434.9)); 29 | list.add(new Person(23, "nihoa", 234.9)); 30 | list.add(new Person(122, "noa", 23434.9)); 31 | 32 | bing.writeExcel("/Users/shi/workspace/aa/adb.xlsx", list); 33 | bing.writeCSV("/Users/shi/workspace/aa/adb.csv", list); 34 | /* try (FileOutputStream os = new FileOutputStream("D:/aoptest/adb1.csv")){ 35 | //bing.writeCSV("D:/aoptest/adb.csv",list); 36 | bing.writeCSV(os,list); 37 | } catch (IOException e) { 38 | e.printStackTrace(); 39 | }*/ 40 | //bing.writeExcel("D:/aoptest/adb.xlsx", list,list,list); 41 | } 42 | 43 | @OutAlias("xiaoshou") 44 | public static class Person { 45 | 46 | public Person(int age, String name, Double salary) { 47 | super(); 48 | this.age = age; 49 | this.name = name; 50 | this.salary = salary; 51 | } 52 | 53 | public Person() { 54 | super(); 55 | } 56 | 57 | @CellConfig(index = 1, aliasName = "年龄") 58 | private int age; 59 | @CellConfig(index = 0) 60 | private String name; 61 | @CellConfig(index = 3) 62 | private Double salary; 63 | @CellConfig(index = 2,readRequired = true,aliasName = "玩玩") 64 | @BingConvertor(value = BooleanFieldConverter.class, strings = { "1","0" }, booleans = { true }) 65 | private boolean testProperty = false; 66 | 67 | public String getName() { 68 | return name; 69 | } 70 | 71 | public void setName(String name) { 72 | this.name = name; 73 | } 74 | 75 | public int getAge() { 76 | return age; 77 | } 78 | 79 | public Double getSalary() { 80 | return salary; 81 | } 82 | 83 | public String toString() { 84 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues().add("name", name).add("age", age) 85 | .add("salary", salary).toString(); 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/LinkedTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import java.lang.reflect.Array; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.Date; 7 | import java.util.HashSet; 8 | import java.util.Iterator; 9 | import java.util.LinkedList; 10 | 11 | import org.junit.Test; 12 | 13 | public class LinkedTest { 14 | @Test 15 | public void testTime(){ 16 | 17 | /*System.out.println(getArrayListTime()); 18 | System.out.println("--------------"); 19 | System.out.println(getLinkedArrayTime());*/ 20 | byte a='a'; 21 | byte c=78; 22 | char b='a'; 23 | System.out.println(a); 24 | System.out.println(c); 25 | System.out.println(b); 26 | int i=23; 27 | double d=(double)i; 28 | System.out.println(d); 29 | } 30 | 31 | public long getArrayListTime(){ 32 | Collection cl = new ArrayList(); 33 | long start = System.currentTimeMillis(); 34 | for(int i = 0; i < 1000000; i++){ 35 | cl.add(new Date()); 36 | cl.add("a"); 37 | } 38 | 39 | 40 | return System.currentTimeMillis() - start; 41 | } 42 | public long getLinkedArrayTime(){ 43 | 44 | Collection cl = new LinkedList(); 45 | long start = System.currentTimeMillis(); 46 | for(int i = 0; i < 1000000; i++){ 47 | cl.add(new Date()); 48 | cl.add("a"); 49 | } 50 | 51 | 52 | return System.currentTimeMillis() - start; 53 | } 54 | 55 | @Test 56 | public void arrayTest(){ 57 | int[] arr={1,12,45,63,25}; 58 | Object b=arr; 59 | 60 | //_____-----以上模仿传过来的参数b--------------- 61 | Class type = b.getClass().getComponentType(); 62 | Object[] arrObj=null; 63 | int length = Array.getLength(b); 64 | for(int i=0;i vo = bing.readFile(f, Person.class, 1); 28 | System.out.println(vo.getSheetIndex()); 29 | System.out.println(vo.getSheetName()); 30 | System.out.println(vo.getObjectList()); 31 | } catch (Exception e) { 32 | e.printStackTrace(); 33 | } 34 | 35 | } 36 | 37 | //ceshi 38 | @Test 39 | public void readExcelTest2() throws URISyntaxException { 40 | InputStream in = Person.class.getResourceAsStream("/person.xls"); 41 | 42 | BingExcel bing = BingExcelBuilder.builderInstance(); 43 | try { 44 | SheetVo vo = bing.readStream(in, Person.class, 1); 45 | System.out.println(vo.getSheetIndex()); 46 | System.out.println(vo.getSheetName()); 47 | System.out.println(vo.getObjectList()); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | }finally{ 51 | if(in!=null){ 52 | try { 53 | in.close(); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | } 59 | 60 | } 61 | public static class Person { 62 | @CellConfig(index = 1) 63 | private int age; 64 | //@CellConfig(index = 0,readRequired=true) 65 | @CellConfig(index = 0) 66 | private String name; 67 | @CellConfig(index = 3) 68 | private Double salary; 69 | private int gongling; 70 | 71 | public int getGongling() { 72 | return gongling; 73 | } 74 | 75 | public void setGongling(int gongling) { 76 | this.gongling = gongling; 77 | } 78 | 79 | public String getName() { 80 | return name; 81 | } 82 | 83 | public void setName(String name) { 84 | this.name = name; 85 | } 86 | 87 | public int getAge() { 88 | return age; 89 | } 90 | 91 | public Double getSalary() { 92 | return salary; 93 | } 94 | 95 | public String toString() { 96 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 97 | .add("name", name).add("age", age).add("salary", salary).add("gl",gongling) 98 | .toString(); 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTest7.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Type; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.text.ParseException; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import org.apache.commons.lang3.StringUtils; 12 | import org.junit.Test; 13 | 14 | import com.bing.excel.annotation.CellConfig; 15 | import com.bing.excel.annotation.OutAlias; 16 | import com.bing.excel.converter.AbstractFieldConvertor; 17 | import com.bing.excel.core.BingExcel; 18 | import com.bing.excel.core.BingExcelBuilder; 19 | import com.bing.excel.core.ReaderCondition; 20 | import com.bing.excel.core.handler.ConverterHandler; 21 | import com.bing.excel.core.impl.BingExcelImpl.SheetVo; 22 | import com.bing.utils.StringParseUtil; 23 | import com.google.common.base.MoreObjects; 24 | 25 | /** 26 | * @author shizhongtao 27 | * 28 | * date 2016-3-23 Description: 29 | */ 30 | public class ReadTest7 { 31 | 32 | @Test 33 | public void readExcelTest() throws URISyntaxException { 34 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 35 | URL url = Salary.class.getResource("/salary7.xlsx"); 36 | File f = new File(url.toURI()); 37 | 38 | BingExcel bing = BingExcelBuilder.toBuilder().registerFieldConverter(Date.class, new MyDateConverter()).builder(); 39 | try { 40 | ReaderCondition condition = new ReaderCondition<>(0, 1, 41 | Salary.class); 42 | SheetVo vo = bing.readFile(f, condition); 43 | List objectList = vo.getObjectList(); 44 | for (Object object : objectList) { 45 | System.out.println(object); 46 | for (Date item : ((Salary)object).workingTime) { 47 | System.out.println(item); 48 | } 49 | } 50 | } catch (Exception e) { 51 | e.printStackTrace(); 52 | } 53 | 54 | } 55 | 56 | @OutAlias("hghg") 57 | public static class Salary { 58 | 59 | @CellConfig(index = 1) 60 | private String employNum; 61 | @CellConfig(index = 10) 62 | private Date[] workingTime; 63 | @CellConfig(index = 11) 64 | private String[] team; 65 | 66 | public String toString() { 67 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 68 | .add("employNum", employNum) 69 | .add("workingTime", workingTime).add("team", team) 70 | .toString(); 71 | } 72 | } 73 | public static class MyDateConverter extends AbstractFieldConvertor{ 74 | 75 | @Override 76 | public boolean canConvert(Class clz) { 77 | 78 | return Date.class.isAssignableFrom(clz); 79 | } 80 | 81 | @Override 82 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 83 | if (StringUtils.isBlank(cell)) { 84 | return null; 85 | } 86 | try { 87 | return StringParseUtil.convertYMDT2Date(cell); 88 | } catch (ParseException e) { 89 | 90 | throw new RuntimeException(e); 91 | } 92 | } 93 | 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/collections/ArrayConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.collections; 2 | 3 | import java.lang.reflect.Array; 4 | import java.lang.reflect.Type; 5 | 6 | import com.bing.excel.converter.AbstractFieldConvertor; 7 | import com.bing.excel.converter.FieldValueConverter; 8 | import com.bing.excel.core.handler.ConverterHandler; 9 | import com.bing.excel.exception.ConversionException; 10 | import com.bing.excel.vo.OutValue; 11 | 12 | import com.google.common.base.Strings; 13 | 14 | /** 15 | * @author shizhongtao 16 | * 17 | * date 2016-3-24 18 | * Description: 19 | */ 20 | // TODO 等待完善 21 | @Deprecated 22 | public class ArrayConverter extends AbstractFieldConvertor { 23 | 24 | 25 | 26 | private final String splitCharacter; 27 | public final static String SPACE_SPLIT=" "; 28 | public final static String SPACE_COMMA=","; 29 | public final static String SPACE_SEMICOLON=";"; 30 | 31 | public ArrayConverter() { 32 | splitCharacter=SPACE_COMMA; 33 | } 34 | 35 | public ArrayConverter(String splitCharacter) { 36 | this.splitCharacter=splitCharacter; 37 | } 38 | 39 | @Override 40 | public boolean canConvert(Class clz) { 41 | 42 | return clz.isArray(); 43 | 44 | } 45 | 46 | 47 | @Override 48 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 49 | if(source==null){ 50 | return null; 51 | } 52 | Class type = source.getClass().getComponentType(); 53 | FieldValueConverter converter = converterHandler.getLocalConverter(type); 54 | if(converter==null){ 55 | throw new ConversionException("can find the converter for type [" 56 | + type + "]"); 57 | } 58 | int length = Array.getLength(source); 59 | StringBuilder bd=new StringBuilder(); 60 | for(int i=0;i bingExcelExcleBuilder = BingExcelBuilder.toBuilder(); 37 | BingExcel bing = bingExcelExcleBuilder 38 | .addFieldConversionMapper(Salary.class,"name",2).registerFieldConverter(Date.class, new MyDateConverter()).build(); 39 | try { 40 | //ReaderCondition condition = new ReaderCondition<>(0, 1, 41 | // Salary.class); 42 | SheetVo vo = bing.readFile(f, Salary.class,1); 43 | List objectList = vo.getObjectList(); 44 | for (Object o : objectList) { 45 | System.out.println(o); 46 | } 47 | // bing.writeExcel("/Users/shi/workspace/gaoxinqu/a.xlsx",objectList); 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | 52 | } 53 | 54 | 55 | @OutAlias("hghg") 56 | public static class Salary { 57 | 58 | @CellConfig(index = 1) 59 | private String employNum; 60 | @CellConfig(index = 9) 61 | 62 | private Date workingTime; 63 | 64 | private String name; 65 | 66 | public String toString() { 67 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 68 | .add("employNum", employNum) 69 | .add("workingTime", workingTime).add("name",name) 70 | .toString(); 71 | } 72 | } 73 | public static class MyDateConverter extends AbstractFieldConvertor{ 74 | 75 | @Override 76 | public boolean canConvert(Class clz) { 77 | 78 | return Date.class.isAssignableFrom(clz); 79 | } 80 | 81 | @Override 82 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 83 | if (StringUtils.isBlank(cell)) { 84 | return null; 85 | } 86 | try { 87 | return StringParseUtil.convertYMDT2Date(cell); 88 | } catch (ParseException e) { 89 | 90 | throw new RuntimeException(e); 91 | } 92 | } 93 | 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/BingExcelEventBuilder.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | 4 | import com.bing.excel.core.handler.ConverterHandler; 5 | import com.bing.common.ExcleBuilder; 6 | import com.bing.excel.converter.FieldValueConverter; 7 | import com.bing.excel.core.handler.LocalConverterHandler; 8 | import com.bing.excel.core.impl.BingExcelEventImpl; 9 | 10 | /** 11 | *

12 | * Title: BingExcelBuilder</p> 13 | *

14 | * Description: BingExcel的构造类,可以添加自定义转换器等。</p> 15 | *

16 | * Company: chinamobile</p> 17 | * 18 | * @author zhongtao.shi 19 | * date 2015-12-8 20 | * @Deprecated 不建议使用,如果要每次都输出,建议使用ExcelReadFactory 21 | */ 22 | /** 23 | *

24 | * Title: BingExcelBuilder</p> 25 | *

26 | * Description: </p> 27 | *

28 | * Company: chinamobile</p> 29 | * 30 | * @author zhongtao.shi 31 | * date 2015-12-8 32 | */ 33 | @Deprecated 34 | public class BingExcelEventBuilder implements ExcleBuilder { 35 | private final ConverterHandler defaultLocalConverterHandler = new LocalConverterHandler(); 36 | 37 | private BingExcelEvent bingExcelEvent; 38 | 39 | /** 40 | *

41 | * Title: </p> 42 | *

43 | * Description:</p> 44 | */ 45 | private BingExcelEventBuilder() { 46 | 47 | } 48 | 49 | public static ExcleBuilder toBuilder() { 50 | 51 | return new BingExcelEventBuilder(); 52 | 53 | } 54 | /** 55 | * @return BingExcelEvent实例 56 | */ 57 | public static BingExcelEvent builderInstance(){ 58 | return (new BingExcelEventBuilder()).builder(); 59 | } 60 | @Override 61 | public ExcleBuilder registerFieldConverter(Class clazz, 62 | FieldValueConverter converter) { 63 | 64 | defaultLocalConverterHandler.registerConverter(clazz, converter); 65 | 66 | return this; 67 | } 68 | 69 | @Deprecated 70 | @Override 71 | public BingExcelEvent builder() { 72 | if (bingExcelEvent == null) { 73 | bingExcelEvent = new BingExcelEventImpl(defaultLocalConverterHandler); 74 | } 75 | 76 | return this.bingExcelEvent; 77 | } 78 | @Override 79 | public BingExcelEvent build() { 80 | if (bingExcelEvent == null) { 81 | bingExcelEvent = new BingExcelEventImpl(defaultLocalConverterHandler); 82 | } 83 | 84 | return this.bingExcelEvent; 85 | } 86 | 87 | @Override 88 | public ExcleBuilder addFieldConversionMapper(Class clazz, String filedName, 89 | int index) { 90 | return null; 91 | } 92 | 93 | @Override 94 | public ExcleBuilder addFieldConversionMapper(Class clazz, String filedName, 95 | int index, String alias) { 96 | return null; 97 | } 98 | 99 | @Override 100 | public ExcleBuilder addFieldConversionMapper(Class clazz, String filedName, 101 | int index, String alias, FieldValueConverter converter) { 102 | return null; 103 | } 104 | 105 | @Override 106 | public ExcleBuilder addClassNameAlias(Class clazz, String alias) { 107 | return null; 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/vo/ListRow.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.vo; 2 | 3 | import com.google.common.collect.ImmutableList; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collections; 7 | import java.util.Iterator; 8 | import java.util.List; 9 | 10 | 11 | /** 12 | * listrow 对象 13 | * 14 | * @author shizhongtao 15 | * 16 | * date 2016-2-17 Description: 17 | */ 18 | public class ListRow implements Iterable> { 19 | private List> list = null; 20 | private int minIndex = -1; 21 | private int maxIndex = -1; 22 | 23 | /** 24 | * 会创建一个新的arraylist 对象。 25 | * 26 | * @return 返回新的list对象 27 | */ 28 | @Deprecated 29 | public List> getList() { 30 | if (list == null) 31 | return Collections.emptyList(); 32 | return ImmutableList.copyOf(list); 33 | } 34 | 35 | public ListRow add(CellKV kv) { 36 | if (list == null) { 37 | list = new ArrayList<>(); 38 | } 39 | list.add(kv); 40 | int index = kv.getIndex(); 41 | if (index < 0) { 42 | throw new IllegalArgumentException("CellKV 中index不合法"); 43 | } 44 | if (index > maxIndex) { 45 | maxIndex = index; 46 | } 47 | if (minIndex == -1) { 48 | minIndex = index; 49 | } else { 50 | if (index < minIndex) { 51 | minIndex = index; 52 | } 53 | } 54 | return this; 55 | } 56 | 57 | public String toString() { 58 | if (list == null) 59 | return Collections.emptyList().toString(); 60 | return list.toString(); 61 | } 62 | 63 | /** 64 | * 返回对应的array对象,如果kv的index没有对应的arr顺序,用null代替 65 | * 66 | * @return 67 | */ 68 | public String[] toFullArray() { 69 | if (maxIndex != -1) { 70 | return toFullArray(maxIndex + 1); 71 | } else { 72 | return new String[0]; 73 | } 74 | } 75 | 76 | /** 77 | * 返回对应的array对象,如果kv的index没有对应的arr顺序,用null代替 78 | * 79 | * @param length 80 | * @return 81 | */ 82 | public String[] toFullArray(int length) { 83 | 84 | String[] arr = new String[length]; 85 | if (maxIndex != -1) { 86 | for (CellKV kv : list) { 87 | if (kv.getIndex() < length) { 88 | arr[kv.getIndex()] = kv.getValue(); 89 | } 90 | } 91 | } 92 | return arr; 93 | 94 | } 95 | 96 | public String[] toArray() { 97 | if (maxIndex != -1) { 98 | String[] arr = new String[list.size()]; 99 | int i=0; 100 | for (CellKV temp : list) { 101 | arr[i]=temp.getValue(); 102 | i++; 103 | } 104 | return arr; 105 | } 106 | return new String[0]; 107 | } 108 | 109 | public void clear() { 110 | if (list != null) { 111 | list.clear(); 112 | 113 | } 114 | maxIndex = -1; 115 | minIndex = -1; 116 | } 117 | 118 | @Override 119 | public Iterator> iterator() { 120 | 121 | if (maxIndex == -1) { 122 | list = new ArrayList>(); 123 | } 124 | return list.iterator(); 125 | } 126 | 127 | public int size() { 128 | if (list != null) { 129 | return list.size(); 130 | } 131 | return 0; 132 | } 133 | 134 | } 135 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTestGlobalConverter6.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Type; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.util.List; 8 | 9 | import org.apache.commons.lang3.StringUtils; 10 | import org.junit.Test; 11 | 12 | import com.bing.excel.annotation.CellConfig; 13 | import com.bing.excel.converter.AbstractFieldConvertor; 14 | import com.bing.excel.core.BingExcel; 15 | import com.bing.excel.core.BingExcelBuilder; 16 | import com.bing.excel.core.ReaderCondition; 17 | import com.bing.excel.core.handler.ConverterHandler; 18 | import com.bing.excel.core.impl.BingExcelImpl.SheetVo; 19 | 20 | import com.google.common.base.MoreObjects; 21 | 22 | /** 23 | * @author shizhongtao 24 | * 25 | * date 2016-3-23 26 | * Description: 27 | */ 28 | public class ReadTestGlobalConverter6 { 29 | 30 | 31 | @Test 32 | public void readExcelTest() throws URISyntaxException { 33 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 34 | URL url = Salary.class.getResource("/salary6.xlsx"); 35 | File f = new File(url.toURI()); 36 | 37 | BingExcel bing = BingExcelBuilder.toBuilder().registerFieldConverter(EmploryAttribute.class, new MyDateConverter()).builder(); 38 | ReaderCondition condition=new ReaderCondition<>(1,Salary.class); 39 | condition.setStartRow(2); 40 | try { 41 | SheetVo vo = bing.readFile(f, condition); 42 | System.out.println(vo.getSheetIndex()); 43 | System.out.println(vo.getSheetName()); 44 | List objectList = vo.getObjectList(); 45 | for (Salary salary : objectList) { 46 | System.out.println(salary); 47 | } 48 | } catch (Exception e) { 49 | e.printStackTrace(); 50 | } 51 | 52 | } 53 | 54 | public static class Salary { 55 | 56 | @CellConfig(index = 1) 57 | private String employNum; 58 | 59 | @CellConfig(index = 0) 60 | private String id; 61 | 62 | @CellConfig(index = 3) 63 | private EmploryAttribute attribute;// 枚举类型 64 | 65 | public String toString() { 66 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 67 | .add("id", id).add("employNum", employNum) 68 | .add("attribute", attribute).toString(); 69 | } 70 | } 71 | 72 | public static class EmploryAttribute { 73 | private String key; 74 | private String value; 75 | 76 | public String toString() { 77 | return MoreObjects.toStringHelper(getClass()).add("key", key) 78 | .add("value", value).toString(); 79 | } 80 | 81 | } 82 | 83 | public static class MyDateConverter extends AbstractFieldConvertor{ 84 | 85 | @Override 86 | public boolean canConvert(Class clz) { 87 | 88 | return EmploryAttribute.class.equals(clz); 89 | } 90 | 91 | @Override 92 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 93 | if(StringUtils.isBlank(cell)){ 94 | return null; 95 | }else{ 96 | String[] split = cell.split(":"); 97 | EmploryAttribute attribute=new EmploryAttribute(); 98 | attribute.key=split[0]; 99 | attribute.value=split[1]; 100 | return attribute; 101 | } 102 | } 103 | 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTestEventModel5.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Type; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.text.ParseException; 8 | import java.util.Date; 9 | 10 | import org.apache.commons.lang3.StringUtils; 11 | import org.junit.Test; 12 | 13 | import com.bing.excel.annotation.BingConvertor; 14 | import com.bing.excel.annotation.CellConfig; 15 | import com.bing.excel.converter.AbstractFieldConvertor; 16 | import com.bing.excel.core.BingExcelEvent; 17 | import com.bing.excel.core.BingExcelEventBuilder; 18 | import com.bing.excel.core.BingReadListener; 19 | import com.bing.excel.core.handler.ConverterHandler; 20 | import com.bing.excel.core.impl.BingExcelEventImpl.ModelInfo; 21 | import com.bing.utils.StringParseUtil; 22 | import com.google.common.base.MoreObjects; 23 | 24 | /** 25 | * @author shizhongtao 26 | * 27 | * date 2016-3-23 28 | * Description: 29 | */ 30 | public class ReadTestEventModel5 { 31 | 32 | @Test 33 | public void readExcelTest() throws URISyntaxException { 34 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 35 | URL url = Salary.class.getResource("/salaryEvent.xlsx"); 36 | File f = new File(url.toURI()); 37 | //event模式读取数据 38 | BingExcelEvent bing = BingExcelEventBuilder.toBuilder().builder(); 39 | try { 40 | long st = System.currentTimeMillis(); 41 | bing.readFile(f, Salary.class, 1,new tempListener()); 42 | System.out.println((System.currentTimeMillis()-st)/1000); 43 | 44 | } catch (Exception e) { 45 | e.printStackTrace(); 46 | } 47 | 48 | } 49 | 50 | enum Department { 51 | develop, personnel, product; 52 | } 53 | 54 | public static class Salary { 55 | 56 | @CellConfig(index = 0) 57 | private String employID; 58 | 59 | 60 | 61 | @CellConfig(index = 13) 62 | @BingConvertor(DateTestConverter.class) 63 | // 自定义转换器 64 | private Date atypiaDate; 65 | @CellConfig(index = 15) 66 | @BingConvertor(DateTestConverter.class) 67 | // 自定义转换器 68 | private Date entryTime; 69 | 70 | 71 | 72 | public String toString() { 73 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 74 | .add("employID", employID) 75 | .add("atypiaDate", atypiaDate) 76 | .add("entryTime", entryTime).toString(); 77 | } 78 | } 79 | 80 | public static class DateTestConverter extends AbstractFieldConvertor { 81 | 82 | 83 | 84 | @Override 85 | public boolean canConvert(Class clz) { 86 | return clz.equals(Date.class); 87 | } 88 | 89 | @Override 90 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 91 | 92 | if (StringUtils.isBlank(cell)) { 93 | return null; 94 | } 95 | try { 96 | return StringParseUtil.convertYMDT2Date(cell); 97 | } catch (ParseException e) { 98 | 99 | throw new RuntimeException(e); 100 | } 101 | } 102 | 103 | 104 | 105 | } 106 | 107 | public static class tempListener implements BingReadListener{ 108 | 109 | @Override 110 | public void readModel(Object object, ModelInfo modelInfo) { 111 | 112 | System.out.println(modelInfo+":"+object); 113 | } 114 | 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/BingExcelBuilder.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | 4 | import com.bing.excel.converter.FieldValueConverter; 5 | import com.bing.excel.core.handler.ConverterHandler; 6 | import com.bing.common.ExcleBuilder; 7 | import com.bing.excel.core.handler.LocalConverterHandler; 8 | import com.bing.excel.core.impl.BingExcelImpl; 9 | 10 | /** 11 | *

12 | * Title: BingExcelBuilder</p> 13 | *

14 | * Description: BingExcel的构造类,可以添加自定义转换器等。</p> 15 | *

16 | * Company: chinamobile</p> 17 | * 18 | * @author zhongtao.shi 19 | * date 2015-12-8 20 | */ 21 | 22 | /** 23 | *

24 | * Title: BingExcelBuilder</p> 25 | *

26 | * Description: </p> 27 | *

28 | * Company: chinamobile</p> 29 | * 30 | * @author zhongtao.shi 31 | * date 2015-12-8 32 | */ 33 | public class BingExcelBuilder implements ExcleBuilder { 34 | 35 | private final ConverterHandler localConverterHandler = new LocalConverterHandler(); 36 | 37 | /** 38 | * bingExcel:对应的excel工具类。 39 | */ 40 | private BingExcel bingExcel; 41 | 42 | /** 43 | *

44 | * Title: </p> 45 | *

46 | * Description: 构造新的builder对象</p> 47 | */ 48 | private BingExcelBuilder() { 49 | 50 | } 51 | 52 | public static ExcleBuilder toBuilder() { 53 | 54 | return new BingExcelBuilder(); 55 | 56 | } 57 | 58 | /** 59 | * @return BingExcel 实例 60 | */ 61 | public static BingExcel builderInstance() { 62 | return (new BingExcelBuilder()).builder(); 63 | } 64 | 65 | @Override 66 | public ExcleBuilder registerFieldConverter(Class clazz, 67 | FieldValueConverter converter) { 68 | localConverterHandler.registerConverter(clazz, converter); 69 | return this; 70 | } 71 | 72 | @Override 73 | public ExcleBuilder addFieldConversionMapper(Class clazz, 74 | String filedName, int index) { 75 | return addFieldConversionMapper(clazz, filedName, index, filedName, null); 76 | 77 | } 78 | 79 | @Override 80 | public ExcleBuilder addFieldConversionMapper(Class clazz, 81 | String filedName, int index, String alias) { 82 | return addFieldConversionMapper(clazz, filedName, index, alias, null); 83 | } 84 | 85 | @Override 86 | public ExcleBuilder addFieldConversionMapper(Class clazz, 87 | String filedName, int index, String alias, FieldValueConverter converter) { 88 | getBingExcel().fieldConverter(clazz, filedName, index, alias, converter); 89 | return this; 90 | } 91 | 92 | @Override 93 | public ExcleBuilder addClassNameAlias(Class clazz, 94 | String alias) { 95 | getBingExcel().modelName(clazz, alias); 96 | return this; 97 | } 98 | 99 | 100 | @Deprecated 101 | @Override 102 | public BingExcel builder() { 103 | if (bingExcel == null) { 104 | bingExcel = new BingExcelImpl(localConverterHandler); 105 | } 106 | 107 | return this.bingExcel; 108 | } 109 | 110 | @Override 111 | public BingExcel build() { 112 | 113 | return this.getBingExcel(); 114 | } 115 | 116 | private BingExcel getBingExcel() { 117 | if (bingExcel == null) { 118 | bingExcel = new BingExcelImpl(localConverterHandler); 119 | } 120 | return this.bingExcel; 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTest2.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Type; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.text.ParseException; 8 | import java.util.Date; 9 | import java.util.List; 10 | 11 | import org.apache.commons.lang3.StringUtils; 12 | import org.junit.Test; 13 | 14 | import com.bing.excel.annotation.BingConvertor; 15 | import com.bing.excel.annotation.CellConfig; 16 | import com.bing.excel.converter.AbstractFieldConvertor; 17 | import com.bing.excel.core.BingExcel; 18 | import com.bing.excel.core.BingExcelBuilder; 19 | import com.bing.excel.core.handler.ConverterHandler; 20 | import com.bing.excel.core.impl.BingExcelImpl.SheetVo; 21 | import com.bing.utils.StringParseUtil; 22 | import com.google.common.base.MoreObjects; 23 | 24 | public class ReadTest2 { 25 | 26 | @Test 27 | public void readExcelTest() throws URISyntaxException { 28 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 29 | URL url = Salary.class.getResource("/salary.xlsx"); 30 | File f = new File(url.toURI()); 31 | 32 | BingExcel bing = BingExcelBuilder.toBuilder().builder(); 33 | 34 | SheetVo vo = null; 35 | try { 36 | vo = bing.readFile(f, Salary.class, 1); 37 | } catch (Exception e) { 38 | e.printStackTrace(); 39 | } 40 | System.out.println(vo.getSheetIndex()); 41 | System.out.println(vo.getSheetName()); 42 | List objectList = vo.getObjectList(); 43 | for (Salary salary : objectList) { 44 | System.out.println(salary); 45 | } 46 | 47 | 48 | } 49 | 50 | public static class Salary { 51 | 52 | @CellConfig(index = 1) 53 | private String employNum; 54 | 55 | @CellConfig(index = 0) 56 | private String id; 57 | 58 | @CellConfig(index = 12) 59 | private Double salary; 60 | 61 | @CellConfig(index = 11) 62 | private double trueSalary; 63 | 64 | @CellConfig(index = 14) 65 | private Date trueDate; 66 | 67 | @CellConfig(index = 13) 68 | @BingConvertor(DateTestConverter.class)//自定义转换器 69 | private Date atypiaDate; 70 | @CellConfig(index = 15) 71 | @BingConvertor(DateTestConverter.class)//自定义转换器 72 | private Date entryTime; 73 | 74 | 75 | 76 | // 其他不对应的属性可以这样定义 77 | private transient String test; 78 | 79 | public String toString() { 80 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 81 | .add("id", id).add("employNum", employNum) 82 | .add("salary", salary).add("trueSalary", trueSalary) 83 | .add("trueDate", trueDate) 84 | .add("atypiaDate", atypiaDate) 85 | .add("entryTime", entryTime) 86 | .toString(); 87 | } 88 | } 89 | 90 | public static class DateTestConverter extends AbstractFieldConvertor { 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | @Override 99 | public boolean canConvert(Class clz) { 100 | return clz.equals(Date.class); 101 | } 102 | 103 | @Override 104 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 105 | if (StringUtils.isBlank(cell)) { 106 | return null; 107 | } 108 | try { 109 | return StringParseUtil.convertYMDT2Date(cell); 110 | } catch (ParseException e) { 111 | 112 | throw new RuntimeException(e); 113 | } 114 | } 115 | 116 | 117 | 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/ReadTestThreadLocal.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.IOException; 8 | import java.util.Date; 9 | 10 | import org.junit.Test; 11 | 12 | import com.bing.excel.annotation.CellConfig; 13 | import com.bing.excel.reader.ExcelReadListener; 14 | import com.bing.excel.reader.ExcelReaderFactory; 15 | import com.bing.excel.reader.ReadHandler; 16 | import com.bing.excel.vo.ListRow; 17 | import com.google.common.base.MoreObjects; 18 | 19 | public class ReadTestThreadLocal { 20 | 21 | @Test 22 | public void readExcelTest() { 23 | System.out.println("start: " + System.currentTimeMillis()); 24 | new ThreadTest().start(); 25 | /*new ThreadTest().start(); 26 | new ThreadTest().start(); 27 | new ThreadTest().start(); 28 | new ThreadTest().start();*/ 29 | 30 | try { 31 | Thread.sleep(25000); 32 | } catch (InterruptedException e) { 33 | // TODO Auto-generated catch block 34 | e.printStackTrace(); 35 | } 36 | } 37 | 38 | public static class ThreadTest extends Thread { 39 | 40 | @Override 41 | public void run() { 42 | /*BingExcelEvent builder = BingExcelEventBuilder.toBuilder() 43 | .builder(); 44 | try { 45 | File f = new File("E:/aoptest/bc.xlsx"); 46 | 47 | builder.readFile(f, Person.class, 1, new BingReadListener() { 48 | 49 | 50 | @Override 51 | public void readModel(Object object, ModelInfo modelInfo) { 52 | 53 | 54 | } 55 | }); 56 | System.out.println(System.currentTimeMillis()); 57 | } catch (Exception e) { 58 | e.printStackTrace(); 59 | }*/ 60 | File f = new File("D:/50.8M.xlsx"); 61 | FileInputStream inputStream = null; 62 | BufferedInputStream bufferedInputStream=null; 63 | try { 64 | inputStream = new FileInputStream(f); 65 | bufferedInputStream = new BufferedInputStream(inputStream,10000); 66 | } catch (FileNotFoundException e) { 67 | e.printStackTrace(); 68 | } 69 | try { 70 | ReadHandler handler = ExcelReaderFactory.create(inputStream, new ExcelReadListener() { 71 | 72 | @Override 73 | public void startSheet(int sheetIndex, String name) { 74 | } 75 | 76 | @Override 77 | public void optRow(int curRow, ListRow rowList) { 78 | if (curRow<20) { 79 | System.out.println(rowList); 80 | } 81 | } 82 | 83 | @Override 84 | public void endWorkBook() { 85 | System.out.println(System.currentTimeMillis()); 86 | } 87 | 88 | @Override 89 | public void endSheet(int sheetIndex, String name) { 90 | } 91 | }); 92 | handler.readSheets(); 93 | } catch (Exception e) { 94 | e.printStackTrace(); 95 | } 96 | try { 97 | inputStream.close(); 98 | } catch (IOException e) { 99 | e.printStackTrace(); 100 | } 101 | 102 | } 103 | 104 | } 105 | 106 | public static class Person { 107 | 108 | @CellConfig(index = 0) 109 | private Date date; 110 | 111 | public Date getDate() { 112 | return date; 113 | } 114 | 115 | public void setDate(Date date) { 116 | this.date = date; 117 | } 118 | 119 | public String toString() { 120 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 121 | .add("date", date).toString(); 122 | } 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/ReadTest3.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.Type; 5 | import java.net.URISyntaxException; 6 | import java.net.URL; 7 | import java.text.ParseException; 8 | import java.text.SimpleDateFormat; 9 | import java.util.Date; 10 | import java.util.List; 11 | 12 | import org.apache.commons.lang3.StringUtils; 13 | import org.junit.Test; 14 | 15 | import com.bing.excel.annotation.BingConvertor; 16 | import com.bing.excel.annotation.CellConfig; 17 | import com.bing.excel.converter.AbstractFieldConvertor; 18 | import com.bing.excel.converter.base.BooleanFieldConverter; 19 | import com.bing.excel.core.BingExcel; 20 | import com.bing.excel.core.BingExcelBuilder; 21 | import com.bing.excel.core.handler.ConverterHandler; 22 | import com.bing.excel.core.impl.BingExcelImpl.SheetVo; 23 | 24 | import com.google.common.base.MoreObjects; 25 | 26 | public class ReadTest3 { 27 | 28 | @Test 29 | public void readExcelTest() throws URISyntaxException { 30 | // InputStream in = Person.class.getResourceAsStream("/person.xlsx"); 31 | URL url = Salary.class.getResource("/salary.xlsx"); 32 | File f = new File(url.toURI()); 33 | 34 | BingExcel bing = BingExcelBuilder.toBuilder().builder(); 35 | try { 36 | SheetVo vo = bing.readFile(f, Salary.class, 1); 37 | System.out.println(vo.getSheetIndex()); 38 | System.out.println(vo.getSheetName()); 39 | List objectList = vo.getObjectList(); 40 | for (Salary salary : objectList) { 41 | System.out.println(salary); 42 | } 43 | } catch (Exception e) { 44 | e.printStackTrace(); 45 | } 46 | 47 | } 48 | 49 | enum Department { 50 | develop, personnel, product; 51 | } 52 | 53 | public static class Salary { 54 | 55 | @CellConfig(index = 1) 56 | private String employNum; 57 | 58 | @CellConfig(index = 0) 59 | private String id; 60 | //默认的boolean类型只支持"TRUE", "FALSE"字符的转换,但是它自带了传参数的构造方法,具体可以参考源码, 61 | @CellConfig(index = 8) 62 | @BingConvertor(value = BooleanFieldConverter.class, strings = { "1","0" }, booleans = { false }) 63 | private boolean allDay; 64 | 65 | @CellConfig(index=7) 66 | private Department department;//枚举类型 67 | 68 | @CellConfig(index = 13) 69 | @BingConvertor(DateTestConverter.class) 70 | // 自定义转换器 71 | private Date atypiaDate; 72 | @CellConfig(index = 14) 73 | private Date entryTime; 74 | 75 | // 其他变量可以这样定义。 76 | private transient String test; 77 | 78 | public String toString() { 79 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 80 | .add("id", id).add("employNum", employNum) 81 | .add("allDay", allDay) 82 | .add("atypiaDate", atypiaDate) 83 | .add("department", department) 84 | .add("entryTime", entryTime).toString(); 85 | } 86 | } 87 | 88 | public static class DateTestConverter extends AbstractFieldConvertor { 89 | 90 | @Override 91 | public boolean canConvert(Class clz) { 92 | return clz.equals(Date.class); 93 | } 94 | @Override 95 | public Object fromString(String cell, ConverterHandler converterHandler,Type type) { 96 | 97 | if (StringUtils.isBlank(cell)) { 98 | return null; 99 | } 100 | try { 101 | //return StringParseUtil.convertYMDT2Date(cell);项目中的util类 102 | SimpleDateFormat format=new SimpleDateFormat("yyyy.MM.dd"); 103 | Date date = format.parse(cell); 104 | return date; 105 | } catch (ParseException e) { 106 | throw new RuntimeException(e); 107 | } 108 | } 109 | 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest2.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Date; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang3.RandomStringUtils; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | 11 | import com.bing.excel.annotation.CellConfig; 12 | import com.bing.excel.annotation.OutAlias; 13 | import com.bing.excel.core.BingExcel; 14 | import com.bing.excel.core.BingExcelBuilder; 15 | import com.google.common.base.MoreObjects; 16 | 17 | public class WriteTest2 { 18 | BingExcel bing; 19 | List list = new ArrayList<>(); 20 | 21 | @Before 22 | public void before() { 23 | bing = BingExcelBuilder.toBuilder().builder(); 24 | for (int i = 0; i < 10000; i++) { 25 | Person p = new Person((int) (Math.random() * 100), 26 | RandomStringUtils.randomAlphanumeric(4), 27 | Math.random() * 1000); 28 | list.add(p); 29 | } 30 | } 31 | 32 | @Test 33 | public void testWrite() { 34 | 35 | WriteThread thread1 = new WriteThread(bing, list); 36 | WriteThread thread2 = new WriteThread(bing, list); 37 | WriteThread thread3 = new WriteThread(bing, list); 38 | WriteThread thread4 = new WriteThread(bing, list); 39 | WriteThread thread5 = new WriteThread(bing, list); 40 | 41 | thread1.start(); 42 | thread2.start(); 43 | thread3.start(); 44 | thread4.start(); 45 | thread5.start(); 46 | try { 47 | Thread.sleep(30000); 48 | } catch (InterruptedException e) { 49 | // TODO Auto-generated catch block 50 | e.printStackTrace(); 51 | } 52 | 53 | } 54 | 55 | public static class WriteThread extends Thread { 56 | BingExcel bing; 57 | List list; 58 | 59 | public WriteThread(BingExcel bing, List list) { 60 | this.bing = bing; 61 | this.list = list; 62 | } 63 | 64 | @Override 65 | public void run() { 66 | 67 | if (Math.random() > 0.4) { 68 | bing.writeExcel("D:/aoptest/adb" 69 | + Thread.currentThread().getName() + ".xlsx", list, 70 | list); 71 | } else { 72 | // chinamobile.writeExcel("E:/aoptest/adb"+Thread.currentThread().getName()+".xlsx", 73 | // list); 74 | bing.writeOldExcel("D:/aoptest/adb" 75 | + Thread.currentThread().getName() + ".xls", list); 76 | } 77 | System.out.println("end:" + Thread.currentThread().getName()); 78 | } 79 | 80 | } 81 | 82 | @OutAlias("xiaoshou") 83 | public static class Person { 84 | 85 | public Person(int age, String name, Double salary) { 86 | super(); 87 | this.age = age; 88 | this.name = name; 89 | this.salary = salary; 90 | this.date = new Date(); 91 | } 92 | 93 | public Person() { 94 | super(); 95 | } 96 | 97 | @CellConfig(index = 1, aliasName = "年龄") 98 | private int age; 99 | @CellConfig(index = 0) 100 | private String name; 101 | @CellConfig(index = 3) 102 | private Double salary; 103 | 104 | @CellConfig(index = 2, aliasName = "日期") 105 | private Date date; 106 | private transient boolean testProperty = false; 107 | private transient String test = "aoptest"; 108 | 109 | public String getName() { 110 | return name; 111 | } 112 | 113 | public void setName(String name) { 114 | this.name = name; 115 | } 116 | 117 | public int getAge() { 118 | return age; 119 | } 120 | 121 | public Double getSalary() { 122 | return salary; 123 | } 124 | 125 | public String toString() { 126 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 127 | .add("name", name).add("age", age).add("salary", salary) 128 | .toString(); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/usermodel/ExcelHSSFDataFormatter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader.usermodel; 2 | 3 | /* ==================================================================== 4 | Licensed to the Apache Software Foundation (ASF) under one or more 5 | contributor license agreements. See the NOTICE file distributed with 6 | this work for additional information regarding copyright ownership. 7 | The ASF licenses this file to You under the Apache License, Version 2.0 8 | (the "License"); you may not use this file except in compliance with 9 | the License. You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | ==================================================================== */ 19 | 20 | import java.text.DecimalFormat; 21 | import java.text.Format; 22 | import java.util.Locale; 23 | 24 | import org.apache.poi.util.LocaleUtil; 25 | 26 | /** 27 | * HSSFDataFormatter contains methods for formatting the value stored in an 28 | * HSSFCell. This can be useful for reports and GUI presentations when you 29 | * need to display data exactly as it appears in Excel. Supported formats 30 | * include currency, SSN, percentages, decimals, dates, phone numbers, zip 31 | * codes, etc. 32 | *

33 | * Internally, formats will be implemented using subclasses of {@link Format} 34 | * such as {@link DecimalFormat} and {@link java.text.SimpleDateFormat}. Therefore the 35 | * formats used by this class must obey the same pattern rules as these Format 36 | * subclasses. This means that only legal number pattern characters ("0", "#", 37 | * ".", "," etc.) may appear in number formats. Other characters can be 38 | * inserted before or after the number pattern to form a 39 | * prefix or suffix. 40 | *

41 | *

42 | * For example the Excel pattern "$#,##0.00 "USD"_);($#,##0.00 "USD")" 43 | * will be correctly formatted as "$1,000.00 USD" or "($1,000.00 USD)". 44 | * However the pattern "00-00-00" is incorrectly formatted by 45 | * DecimalFormat as "000000--". For Excel formats that are not compatible with 46 | * DecimalFormat, you can provide your own custom {@link Format} implementation 47 | * via HSSFDataFormatter.addFormat(String,Format). The following 48 | * custom formats are already provided by this class: 49 | *

50 | *
51 | * 
  • SSN "000-00-0000"
  • 52 | *
  • Phone Number "(###) ###-####"
  • 53 | *
  • Zip plus 4 "00000-0000"
  • 54 | *
55 | *
56 | *

57 | * If the Excel format pattern cannot be parsed successfully, then a default 58 | * format will be used. The default number format will mimic the Excel General 59 | * format: "#" for whole numbers and "#.##########" for decimal numbers. You 60 | * can override the default format pattern with 61 | * HSSFDataFormatter.setDefaultNumberFormat(Format). Note: the 62 | * default format will only be used when a Format cannot be created from the 63 | * cell's data format string. 64 | */ 65 | public final class ExcelHSSFDataFormatter extends ExcelDataFormatter { 66 | 67 | /** 68 | * Creates a formatter using the given locale. 69 | */ 70 | public ExcelHSSFDataFormatter(Locale locale) { 71 | super(locale); 72 | } 73 | 74 | /** 75 | * Creates a formatter using the {@link Locale#getDefault() default locale}. 76 | */ 77 | public ExcelHSSFDataFormatter() { 78 | this(LocaleUtil.getUserLocale()); 79 | } 80 | 81 | } 82 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest4.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import org.apache.commons.lang3.RandomStringUtils; 4 | import org.junit.Before; 5 | import org.junit.Test; 6 | 7 | import com.bing.excel.annotation.CellConfig; 8 | import com.bing.excel.annotation.OutAlias; 9 | import com.bing.excel.core.BingExcelEvent; 10 | import com.bing.excel.core.BingExcelEventBuilder; 11 | import com.bing.excel.core.rw.BingWriterHandler; 12 | import com.google.common.base.MoreObjects; 13 | 14 | /** 15 | * @author shizhongtao 16 | */ 17 | public class WriteTest4 { 18 | BingExcelEvent bing; 19 | 20 | @Before 21 | public void before() { 22 | bing = BingExcelEventBuilder.builderInstance(); 23 | } 24 | 25 | @Test 26 | public void testWrite() { 27 | /** 28 | * 对于数据量非常大时候,注意一点就是数据绝对不能放入到内存, 你如果想初始化一个长多为百万级的list,劝你趁早放弃 29 | */ 30 | BingWriterHandler writerHandler = bing.writeFile("/Users/shi/workspace/student.xlsx"); 31 | writerHandler.writeLine(new Student("a", RandomStringUtils.randomAlphanumeric(4), "cc")); 32 | writerHandler 33 | .writeLine(new Person(23, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 34 | writerHandler.setMaxLineForSheet(100); 35 | for (int i = 0; i < 200; i++) { 36 | if (i > 100 && i < 110) { 37 | writerHandler.writeLine(new Student("a", RandomStringUtils.randomAlphanumeric(4), "cc")); 38 | } 39 | writerHandler 40 | .writeLine(new Person(23, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 41 | } 42 | writerHandler.close(); 43 | } 44 | 45 | @OutAlias("xiaoshou") 46 | public static class Person { 47 | 48 | public Person(int age, String name, Double salary) { 49 | super(); 50 | this.age = age; 51 | this.name = name; 52 | this.salary = salary; 53 | } 54 | 55 | public Person() { 56 | super(); 57 | } 58 | 59 | @CellConfig(index = 1, aliasName = "年龄") 60 | private int age; 61 | @CellConfig(index = 0) 62 | private String name; 63 | @CellConfig(index = 3) 64 | private Double salary; 65 | 66 | public Person getFriends() { 67 | return friends; 68 | } 69 | 70 | public void setFriends(Person friends) { 71 | this.friends = friends; 72 | } 73 | 74 | private Person friends; 75 | 76 | private transient boolean testProperty = false; 77 | 78 | public String getName() { 79 | return name; 80 | } 81 | 82 | public void setName(String name) { 83 | this.name = name; 84 | } 85 | 86 | public int getAge() { 87 | return age; 88 | } 89 | 90 | public Double getSalary() { 91 | return salary; 92 | } 93 | 94 | @Override 95 | public String toString() { 96 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues().add("name", name) 97 | .add("age", age).add("salary", salary).toString(); 98 | } 99 | } 100 | 101 | public static class Student { 102 | @CellConfig(index = 0) 103 | private String schoolName; 104 | @CellConfig(index = 1) 105 | private String className; 106 | @CellConfig(index = 2) 107 | private String name; 108 | 109 | public Student() {} 110 | 111 | public Student(String schoolName, String className, String name) { 112 | this.schoolName = schoolName; 113 | this.className = className; 114 | this.name = name; 115 | } 116 | 117 | @Override 118 | public String toString() { 119 | return MoreObjects.toStringHelper(this).omitNullValues().add("schoolName", schoolName) 120 | .add("className", className).add("name", name).toString(); 121 | } 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/mapper/ConversionMapper.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.mapper; 2 | 3 | import com.bing.excel.converter.FieldValueConverter; 4 | import com.bing.excel.core.common.FieldRelation; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class ConversionMapper { 9 | 10 | private final Map fieldMapper = new HashMap<>(); 11 | private final Map, String> modelAlias = new HashMap<>(); 12 | 13 | public ConversionMapper() { 14 | } 15 | 16 | public void addModelName(Class clazz, String name) { 17 | this.modelAlias.put(clazz, name); 18 | } 19 | 20 | 21 | 22 | public void registerLocalConverter(Class definedIn, String fieldName, 23 | int index, String alias, Class fieldType, boolean readRequired, 24 | FieldValueConverter converter) { 25 | 26 | registerLocalConverter(definedIn, fieldName, new FieldConverterMapper( 27 | index, converter, alias, fieldType, readRequired)); 28 | } 29 | 30 | private void registerLocalConverter(Class definedIn, String fieldName, 31 | FieldConverterMapper mapper) { 32 | 33 | mapper.setContainer(definedIn); 34 | fieldMapper.put(new FieldRelation(definedIn, fieldName), mapper); 35 | } 36 | 37 | public FieldValueConverter getLocalConverter(Class definedIn, 38 | String fieldName) { 39 | return fieldMapper.get(new FieldRelation(definedIn, fieldName)) 40 | .getFieldConverter(); 41 | } 42 | 43 | public FieldConverterMapper getLocalConverterMapper(Class definedIn, 44 | String fieldName) { 45 | return fieldMapper.get(new FieldRelation(definedIn, fieldName)); 46 | } 47 | 48 | 49 | public String getAliasName(Class key) { 50 | return modelAlias.get(key); 51 | } 52 | 53 | public static class FieldConverterMapper { 54 | 55 | private int index; 56 | private boolean isPrimitive = true; 57 | private Class clazz; 58 | private FieldValueConverter converter; 59 | private String alias; 60 | private boolean readRequired = false; 61 | 62 | private Class container; 63 | 64 | public Class getContainer() { 65 | return container; 66 | } 67 | 68 | public void setContainer(Class container) { 69 | this.container = container; 70 | } 71 | 72 | public int getIndex() { 73 | return index; 74 | } 75 | 76 | public boolean isPrimitive() { 77 | return isPrimitive; 78 | } 79 | 80 | public Class getFieldClass() { 81 | return clazz; 82 | } 83 | 84 | public String getAlias() { 85 | return alias; 86 | } 87 | 88 | 89 | public boolean isReadRequired() { 90 | return readRequired; 91 | } 92 | 93 | public FieldValueConverter getFieldConverter() { 94 | return converter; 95 | } 96 | 97 | public void setFieldConverter(FieldValueConverter converter) { 98 | this.converter = converter; 99 | } 100 | 101 | public FieldConverterMapper(int index, FieldValueConverter converter, 102 | String alias, Class clazz) { 103 | super(); 104 | this.index = index; 105 | this.isPrimitive = clazz.isPrimitive(); 106 | this.clazz = clazz; 107 | this.alias = alias; 108 | this.converter = converter; 109 | } 110 | 111 | public FieldConverterMapper(int index, FieldValueConverter converter, 112 | String alias, Class clazz, boolean readRequired) { 113 | super(); 114 | this.index = index; 115 | this.isPrimitive = clazz.isPrimitive(); 116 | this.clazz = clazz; 117 | this.alias = alias; 118 | this.readRequired = readRequired; 119 | this.converter = converter; 120 | } 121 | 122 | } 123 | } 124 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/ReadTestThreadLocalGC.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import org.junit.Test; 4 | 5 | public class ReadTestThreadLocalGC { 6 | 7 | 8 | @Test 9 | public void readExcelTest() throws InterruptedException { 10 | 11 | Handler h=new Handler(); 12 | h.printSome(); 13 | //注意此处 14 | h.local=null; 15 | Thread.sleep(1000); 16 | System.out.println("gc1"); 17 | System.gc(); 18 | //System.out.println(h.local.get()); 19 | h=new Handler(); 20 | h.printSome(); 21 | 22 | Thread.sleep(1000); 23 | System.out.println("gc2"); 24 | System.gc(); 25 | ; 26 | } 27 | 28 | 29 | 30 | @Test 31 | public void readExcelTest2() throws InterruptedException { 32 | 33 | //System.out.println(Handler.local); 34 | Thread t1= new Thread(new Runnable() { 35 | 36 | @Override 37 | public void run() { 38 | try { 39 | Thread.sleep(1000); 40 | } catch (InterruptedException e) { 41 | // TODO Auto-generated catch block 42 | e.printStackTrace(); 43 | } 44 | Handler h=new Handler(); 45 | h.printSome(); 46 | //h.local=null; 47 | System.out.println(h.local); 48 | } 49 | }); 50 | Thread t2= new Thread(new Runnable() { 51 | 52 | @Override 53 | public void run() { 54 | try { 55 | Thread.sleep(1000); 56 | } catch (InterruptedException e) { 57 | // TODO Auto-generated catch block 58 | e.printStackTrace(); 59 | } 60 | Handler h=new Handler(); 61 | h.printSome(); 62 | //h.local=null; 63 | System.out.println(h.local); 64 | } 65 | }); 66 | Thread t3= new Thread(new Runnable() { 67 | 68 | @Override 69 | public void run() { 70 | try { 71 | Thread.sleep(1000); 72 | } catch (InterruptedException e) { 73 | // TODO Auto-generated catch block 74 | e.printStackTrace(); 75 | } 76 | Handler h=new Handler(); 77 | h.printSome(); 78 | //h.local=null; 79 | System.out.println(h.local); 80 | } 81 | }); 82 | t1.start(); 83 | t2.start(); 84 | t3.start(); 85 | System.gc(); 86 | System.out.println("gc1"); 87 | System.gc(); 88 | Thread.sleep(3000); 89 | System.out.println("gc2"); 90 | System.gc(); 91 | Thread.sleep(1000); 92 | System.gc(); 93 | //System.out.println(Handler.local); 94 | 95 | } 96 | 97 | public static class Handler{ 98 | static ThreadMyLocal local; 99 | 100 | private Person getPerson() { 101 | if(local==null){ 102 | local=new ThreadMyLocal<>(); 103 | } 104 | if(local.get()==null){ 105 | Person person = new Person(); 106 | person.setAge(((Double)(Math.random()*100)).intValue()); 107 | local.set(person); 108 | } 109 | return local.get(); 110 | } 111 | 112 | 113 | public void printSome(){ 114 | 115 | Person person = getPerson(); 116 | System.out.println(person.getAge()+":Person对象age属性"); 117 | } 118 | 119 | 120 | @Override 121 | protected void finalize() throws Throwable { 122 | System.out.println("Handler GC"); 123 | super.finalize(); 124 | } 125 | 126 | } 127 | 128 | 129 | 130 | 131 | public static class ThreadMyLocal extends ThreadLocal { 132 | 133 | 134 | 135 | @Override 136 | protected void finalize() throws Throwable { 137 | System.out.println("threadLocal gc:"); 138 | super.finalize(); 139 | } 140 | 141 | } 142 | 143 | public static class Person { 144 | 145 | private int age; 146 | 147 | public int getAge() { 148 | return age; 149 | } 150 | public void setAge(int age) { 151 | this.age = age; 152 | } 153 | 154 | @Override 155 | protected void finalize() { 156 | System.out.println("Person gc"); 157 | } 158 | 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/base/DateFieldConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.base; 2 | 3 | import java.lang.reflect.Type; 4 | import java.text.ParseException; 5 | import java.text.SimpleDateFormat; 6 | import java.util.Collections; 7 | import java.util.Date; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | import com.bing.excel.core.handler.ConverterHandler; 12 | import com.bing.excel.exception.ConversionException; 13 | import com.bing.excel.converter.AbstractFieldConvertor; 14 | import com.bing.excel.vo.OutValue; 15 | 16 | /** 17 | * @author shizhongtao 18 | * 19 | * date 2016-3-21 Description: 20 | */ 21 | public final class DateFieldConverter extends AbstractFieldConvertor { 22 | 23 | private static final ThreadLocal> localFormat = new ThreadLocal<>(); 24 | private final String inFormatStr; 25 | private final String outFormatStr; 26 | private final String inFormatKey = "inKey"; 27 | private final String outFormatKey = "outKey"; 28 | 29 | public DateFieldConverter(boolean smartConversion) { 30 | this("yyyy-MM-dd HH:mm:ss", smartConversion); 31 | } 32 | 33 | public DateFieldConverter() { 34 | this(false); 35 | } 36 | 37 | public DateFieldConverter(String formats, boolean smartConversion) { 38 | this(formats, formats, smartConversion); 39 | } 40 | 41 | public DateFieldConverter(String inFormats, String outFormats, 42 | boolean smartConversion) { 43 | this.inFormatStr = inFormats; 44 | this.outFormatStr = outFormats; 45 | } 46 | 47 | @Override 48 | public boolean canConvert(Class clz) { 49 | return clz.equals(Date.class); 50 | } 51 | 52 | @Override 53 | public OutValue toObject(Object source,ConverterHandler converterHandler) { 54 | if(source==null){ 55 | return null; 56 | } 57 | return OutValue.dateValue(source); 58 | } 59 | 60 | @Override 61 | public Object fromString(String cell,ConverterHandler converterHandler,Type targetType) { 62 | 63 | 64 | String temp=cell; 65 | SimpleDateFormat inFormat=getFormat(outFormatKey); 66 | 67 | if(inFormat==null){ 68 | throw new NullPointerException("inFormat[SimpleDateFormat] is null"); 69 | } 70 | Date date; 71 | try { 72 | date = inFormat.parse(temp); 73 | return date; 74 | } catch (ParseException e) { 75 | try { 76 | inFormat.applyPattern("yy-MM-dd HH:mm"); 77 | date = inFormat.parse(temp); 78 | return date; 79 | } catch (ParseException e1) { 80 | try { 81 | inFormat.applyPattern("yy-MM-dd"); 82 | date = inFormat.parse(temp); 83 | return date; 84 | } catch (ParseException e2) { 85 | throw new ConversionException("Cannot parse date" + cell, e2); 86 | } 87 | } 88 | 89 | } 90 | 91 | } 92 | 93 | public SimpleDateFormat getFormat(String key) { 94 | if (key.equals(inFormatKey)) { 95 | Map map = localFormat.get(); 96 | if (map == null) { 97 | map = Collections.synchronizedMap(new HashMap<>()); 98 | localFormat.set(map); 99 | } 100 | Object object = map.get(key); 101 | if (object == null) { 102 | SimpleDateFormat format = new SimpleDateFormat(inFormatStr); 103 | map.put(key, format); 104 | object = format; 105 | 106 | } 107 | return (SimpleDateFormat) object; 108 | } else if (key.equals(outFormatKey)) { 109 | Map map = localFormat.get(); 110 | if (map == null) { 111 | map = Collections.synchronizedMap(new HashMap<>()); 112 | localFormat.set(map); 113 | } 114 | Object object = map.get(key); 115 | if (object == null) { 116 | SimpleDateFormat format = new SimpleDateFormat(outFormatStr); 117 | map.put(key, format); 118 | object = format; 119 | } 120 | return (SimpleDateFormat) object; 121 | } 122 | return null; 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/hssf/DefaultHSSFHandler.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader.hssf; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.sql.SQLException; 8 | 9 | import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 10 | import org.apache.poi.poifs.filesystem.POIFSFileSystem; 11 | import org.xml.sax.SAXException; 12 | 13 | import com.bing.excel.reader.ExcelReadListener; 14 | import com.bing.excel.reader.ReadHandler; 15 | import com.bing.excel.vo.ListRow; 16 | 17 | /** 18 | * @author shizhongtao 19 | * 20 | * date 2016-2-17 Description: 21 | */ 22 | public class DefaultHSSFHandler extends HSSFListenerAbstract implements 23 | ReadHandler { 24 | 25 | private ExcelReadListener excelReader; 26 | 27 | @Override 28 | public void readSheets(int maxReadLine) throws IOException, 29 | OpenXML4JException, SAXException { 30 | setMaxReturnLine(maxReadLine); 31 | readSheets(); 32 | } 33 | 34 | @Override 35 | public void readSheet(int index, int maxReadLine) throws IOException, 36 | OpenXML4JException, SAXException { 37 | setMaxReturnLine(maxReadLine); 38 | readSheet(index); 39 | } 40 | 41 | @Override 42 | public void readSheet(int[] indexs, int maxReadLine) throws IOException, 43 | OpenXML4JException, SAXException { 44 | setMaxReturnLine(maxReadLine); 45 | readSheet(indexs); 46 | 47 | } 48 | 49 | @Override 50 | public void readSheet(String indexName, int maxReadLine) 51 | throws IOException, OpenXML4JException, SAXException { 52 | setMaxReturnLine(maxReadLine); 53 | readSheet(indexName); 54 | } 55 | 56 | public DefaultHSSFHandler(String path, ExcelReadListener excelReader) 57 | throws FileNotFoundException, IOException, SQLException { 58 | this(path, excelReader, false); 59 | } 60 | 61 | public DefaultHSSFHandler(InputStream in, ExcelReadListener excelReader) 62 | throws SQLException, IOException { 63 | this(in, excelReader, false); 64 | } 65 | 66 | public DefaultHSSFHandler(POIFSFileSystem fs, ExcelReadListener excelReader) 67 | throws SQLException { 68 | this(fs, excelReader, false); 69 | 70 | } 71 | 72 | public DefaultHSSFHandler(String path, ExcelReadListener excelReader, 73 | boolean ignoreNumFormat) throws FileNotFoundException, IOException, 74 | SQLException { 75 | this(new FileInputStream(path), excelReader, ignoreNumFormat); 76 | 77 | } 78 | 79 | public DefaultHSSFHandler(InputStream in, ExcelReadListener excelReader, 80 | boolean ignoreNumFormat) throws SQLException, IOException { 81 | this(new POIFSFileSystem(in), excelReader, ignoreNumFormat); 82 | 83 | } 84 | 85 | public DefaultHSSFHandler(POIFSFileSystem fs, 86 | ExcelReadListener excelReader, boolean ignoreNumFormat) 87 | throws SQLException { 88 | super(fs, excelReader, ignoreNumFormat); 89 | this.excelReader = excelReader; 90 | } 91 | 92 | @Override 93 | public void readSheets() throws IOException, OpenXML4JException, 94 | SAXException { 95 | process(); 96 | 97 | } 98 | 99 | @Override 100 | public void readSheet(int index) throws IOException, OpenXML4JException, 101 | SAXException { 102 | readSheet(new int[] { index }); 103 | } 104 | 105 | @Override 106 | public void readSheet(int[] indexs) throws IOException, OpenXML4JException, 107 | SAXException { 108 | if (indexs.length >= 0) { 109 | setAimSheetIndex(indexs); 110 | } 111 | process(); 112 | } 113 | 114 | @Override 115 | public void readSheet(String indexName) throws IOException, 116 | OpenXML4JException, SAXException { 117 | setAimSheetName(indexName); 118 | process(); 119 | } 120 | 121 | @Override 122 | public void optRows(int sheetIndex, int curRow, ListRow rowlist) 123 | { 124 | excelReader.optRow(curRow, rowlist); 125 | } 126 | 127 | } 128 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/utils/DataTypeDetect.java: -------------------------------------------------------------------------------- 1 | package com.bing.utils; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | /** 7 | * @author shizhongtao 8 | * 9 | * date 2016-2-17 Description: 10 | */ 11 | public class DataTypeDetect { 12 | private static final Pattern DATE_PTRN = Pattern 13 | .compile("^(?:(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})-(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01]))" 14 | + "|(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})-(?:0[13456789]|1[012])-(?:0[1-9]|[12]\\d|30))" 15 | + "|(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})-02-(?:0[1-9]|1\\d|2[0-9])))" 16 | + "\\s+(?:20|21|22|23|[0-1]\\d):[0-5]\\d:[0-5]\\d$"); 17 | private static final Pattern DATE_PTRN1 = Pattern 18 | .compile("^(?:(?:(?:(?:1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_](?:0?[13578]|1[02])[-/\\\\月_](0?[1-9]|[12]\\d|3[01]))" 19 | + "|(?:(?:(?:1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_](?:0?[13456789]|1[012])[-/\\\\月_](0?[1-9]|[12]\\d|30))" 20 | + "|(((1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_]0?2[-/\\\\月_](?:0?[1-9]|1\\d|2[0-9])))" 21 | + "(?:\\s+|[日号]\\s*)(?:20|21|22|23|[0-1]?\\d)[:时点][0-5]?\\d(?:[:分]([0-5]?\\d秒?)|分?){0,1}\\s*$"); 22 | private static final Pattern DATE_PTRN2 = Pattern 23 | .compile("^(?:(?:(?:(?:1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_](?:0?[13578]|1[02])[-/\\\\月_](0?[1-9]|[12]\\d|3[01])[日号]{0,1})" 24 | + "|(?:(?:(?:1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_](?:0?[13456789]|1[012])[-/\\\\月_](0?[1-9]|[12]\\d|30)[日号]{0,1})" 25 | + "|(?:(?:(?:1[6-9]|[2-9]\\d){0,1}\\d{2})[-/\\\\年_]0?2[-/\\\\月_](?:0?[1-9]|1\\d|2[0-9])[日号]{0,1}))" 26 | + "(?:\\s*|(?:\\s+0{1,2}:0{1,2}:0{1,2}))$"); 27 | /*private static final Pattern DATE_PTRN3 = Pattern 28 | .compile("^(?:(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})(?:0[13578]|1[02])(?:0[1-9]|[12]\\d|3[01]))" 29 | + "|(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})(?:0[13456789]|1[012])(?:0[1-9]|[12]\\d|30))" 30 | + "|(?:(?:(?:1[6-9]|[2-9]\\d)\\d{2})02(?:0[1-9]|1\\d|2[0-9])))" 31 | + "$");*/ 32 | private static final Pattern NUMBER_PTRN = Pattern 33 | .compile("^(?:0|[1-9]\\d*)(?:\\.\\d*)?$"); 34 | private static final Pattern INTEGER_PTRN = Pattern 35 | .compile("^(?:0|[1-9]\\d*)(?:\\.0*)?$"); 36 | private static final Pattern BOOLEAN_PTRN = Pattern.compile("^[01是否真假]$"); 37 | 38 | /** 39 | * @author shizhongtao 40 | * @param arg 41 | * @return 42 | */ 43 | public static boolean isYMDT(String arg) { 44 | Matcher m = DATE_PTRN1.matcher(arg); 45 | return m.matches(); 46 | } 47 | 48 | /** 49 | * 如果所给字符串中 时分秒都是0,也返回true 50 | * 51 | * @author shizhongtao 52 | * @return 53 | */ 54 | public static boolean isYMD(String arg) { 55 | boolean re = false; 56 | /*Matcher m3 = DATE_PTRN3.matcher(arg); 57 | if (m3.matches()) { 58 | re = true; 59 | }*/ 60 | if (!re) { 61 | Matcher m = DATE_PTRN2.matcher(arg); 62 | re=m.matches(); 63 | } 64 | return re; 65 | } 66 | 67 | /** 68 | * 判读参数是不是日期类型
69 | * 支持的格式为 (年月日时分秒)顺序的字符串。
70 | * 例如:1900年1月12日,1900-1-12 12:12:10等 71 | * 72 | * @param arg 73 | * @return 74 | */ 75 | public static boolean isDateType(String arg) { 76 | boolean result = false; 77 | Matcher m = DATE_PTRN.matcher(arg); 78 | result = m.matches(); 79 | if (!result) { 80 | result = isYMDT(arg); 81 | } 82 | if (!result) { 83 | result = isYMD(arg); 84 | } 85 | return result; 86 | } 87 | 88 | public static boolean isNumType(String arg) { 89 | Matcher m = NUMBER_PTRN.matcher(arg); 90 | return m.matches() ; 91 | } 92 | 93 | /** 94 | * 只要可以无损转换为整形的都认为是int类型,没有考虑int范围例如:12.0000 95 | * 96 | * @param arg 97 | * @return 98 | */ 99 | public static boolean isIntegerType(String arg) { 100 | Matcher m = INTEGER_PTRN.matcher(arg); 101 | if(!m.matches()){ 102 | return false; 103 | } 104 | String str = arg.replaceFirst("\\.\\d*", ""); 105 | 106 | 107 | return ( str.length()<=String.valueOf(Integer.MAX_VALUE).length()&& ("2147483647".compareTo(str)>0)); 108 | 109 | } 110 | 111 | /** 112 | * @param arg 113 | * @return 114 | */ 115 | public static boolean isBooleanType(String arg) { 116 | Matcher m = BOOLEAN_PTRN.matcher(arg); 117 | return m.matches(); 118 | 119 | } 120 | } 121 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/converter/collections/CollectionConverter.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.converter.collections; 2 | 3 | import java.lang.reflect.ParameterizedType; 4 | import java.lang.reflect.Type; 5 | import java.util.ArrayList; 6 | import java.util.Collection; 7 | import java.util.HashSet; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | import java.util.Set; 11 | 12 | import com.bing.excel.converter.FieldValueConverter; 13 | import com.bing.excel.core.handler.ConverterHandler; 14 | import com.bing.excel.exception.ConversionException; 15 | import com.bing.excel.converter.AbstractFieldConvertor; 16 | import com.bing.excel.vo.OutValue; 17 | import com.google.common.base.Strings; 18 | import com.google.common.collect.Lists; 19 | import com.google.common.collect.Sets; 20 | 21 | /** 22 | * @author shizhongtao 23 | * 24 | * date 2016-3-24 25 | * Description: 26 | */ 27 | // TODO 等待完善 28 | @Deprecated 29 | public class CollectionConverter extends AbstractFieldConvertor { 30 | private final String splitCharacter; 31 | public final static String SPACE_SPLIT=" "; 32 | public final static String SPACE_COMMA=","; 33 | public final static String SPACE_SEMICOLON=";"; 34 | 35 | public CollectionConverter() { 36 | splitCharacter=SPACE_COMMA; 37 | } 38 | 39 | @Override 40 | public boolean canConvert(Class type) { 41 | return type.equals(ArrayList.class) ||type.equals(List.class)|| type.equals(HashSet.class)||type.equals(Set.class) 42 | || type.equals(LinkedList.class); 43 | } 44 | 45 | @Override 46 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 47 | if(source==null){ 48 | return null; 49 | } 50 | Collection collection = (Collection)source; 51 | StringBuilder bd=new StringBuilder(); 52 | for (Object obj : collection) { 53 | Class class1 = obj.getClass(); 54 | FieldValueConverter converter = converterHandler.getLocalConverter(class1); 55 | if(converter==null){ 56 | throw new ConversionException("can find the converter for type [" 57 | + class1 + "]"); 58 | } 59 | OutValue outValue = converter.toObject(obj, converterHandler); 60 | bd.append(outValue.getValue()); 61 | bd.append(splitCharacter); 62 | } 63 | StringBuilder builder = bd.replace(bd.length()-1, bd.length(), ""); 64 | return OutValue.stringValue(builder.toString()); 65 | } 66 | 67 | @Override 68 | public Object fromString(String cell, ConverterHandler converterHandler, 69 | Type targetType) { 70 | if(Strings.isNullOrEmpty(cell)){ 71 | return null; 72 | } 73 | if(targetType==null){ 74 | return null; 75 | } 76 | Collection collection = (Collection) createCollection(targetType); 77 | if(collection==null) { 78 | return null; 79 | } 80 | Class genericsClass = getGenericsClass(targetType); 81 | FieldValueConverter converter = converterHandler.getLocalConverter(genericsClass); 82 | if(converter==null){ 83 | throw new ConversionException("can find the converter for type [" 84 | + genericsClass + "]"); 85 | } 86 | 87 | String[] splitArr = cell.split(splitCharacter); 88 | 89 | for (int i = 0; i < splitArr.length; i++) { 90 | Object object = converter.fromString(splitArr[i], converterHandler,genericsClass); 91 | collection.add(object); 92 | } 93 | 94 | return collection; 95 | } 96 | 97 | private Collection createCollection(Type type) { 98 | if (type == null) { 99 | return null; 100 | } 101 | if(type.equals(ArrayList.class)||type.equals(List.class)){ 102 | return Lists.newArrayList(); 103 | }else if(type.equals(HashSet.class)||type.equals(Set.class)){ 104 | return Sets.newHashSet(); 105 | }else if(type.equals(LinkedList.class)){ 106 | return Lists.newArrayList(); 107 | }else{ 108 | return null; 109 | } 110 | 111 | } 112 | private Class getGenericsClass(Type fc ) { 113 | Class fieldClazz; 114 | if (fc instanceof ParameterizedType) // 如果是泛型参数的类型 115 | { 116 | ParameterizedType pt = (ParameterizedType) fc; 117 | 118 | fieldClazz = (Class) pt.getActualTypeArguments()[0]; //得到泛型里的class类型对象。 119 | }else{ 120 | fieldClazz=String.class; 121 | } 122 | 123 | return fieldClazz; 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/vo/ListLine.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.vo; 2 | 3 | import com.google.common.collect.ImmutableList; 4 | 5 | import java.util.Collections; 6 | import java.util.Date; 7 | import java.util.ArrayList; 8 | import java.util.List; 9 | 10 | /** 11 | * listrow 对象 12 | * 13 | * @author shizhongtao 14 | * date 2016-2-17 Description: 15 | */ 16 | public class ListLine { 17 | private List> listStr = null; 18 | private List> listDouble = null; 19 | private List> listBoolean = null; 20 | private List> listDate = null; 21 | private List> listLong = null; 22 | private int minIndex = -1; 23 | private int maxIndex = -1; 24 | 25 | @SuppressWarnings("unchecked") 26 | public List> getListStr() { 27 | 28 | return listStr == null ? Collections.EMPTY_LIST : ImmutableList.copyOf(listStr); 29 | } 30 | 31 | @SuppressWarnings("unchecked") 32 | public List> getListDouble() { 33 | return listDouble == null ? Collections.EMPTY_LIST : ImmutableList.copyOf(listDouble); 34 | } 35 | 36 | @SuppressWarnings("unchecked") 37 | public List> getListBoolean() { 38 | return listBoolean == null ? Collections.EMPTY_LIST : ImmutableList.copyOf(listBoolean); 39 | } 40 | 41 | @SuppressWarnings("unchecked") 42 | public List> getListDate() { 43 | return listDate == null ? Collections.EMPTY_LIST : ImmutableList.copyOf(listDate); 44 | } 45 | 46 | @SuppressWarnings("unchecked") 47 | public List> getListLong() { 48 | return listLong == null ? Collections.EMPTY_LIST : ImmutableList.copyOf(listLong); 49 | } 50 | public Object[] toFullArray() { 51 | int maxIndex = this.getMaxIndex(); 52 | Object[] objArr = new Object[maxIndex+1]; 53 | if (maxIndex != -1) { 54 | for (CellKV kv : this.getListStr()) { 55 | objArr[kv.getIndex()] = kv.getValue(); 56 | } 57 | for (CellKV kv : this.getListBoolean()) { 58 | objArr[kv.getIndex()] = kv.getValue(); 59 | } 60 | for (CellKV kv : this.getListDate()) { 61 | objArr[kv.getIndex()] = kv.getValue(); 62 | } 63 | for (CellKV kv : this.getListDouble()) { 64 | objArr[kv.getIndex()] = kv.getValue(); 65 | } 66 | for (CellKV kv : this.getListLong()) { 67 | objArr[kv.getIndex()] = kv.getValue(); 68 | } 69 | } 70 | return objArr; 71 | } 72 | public ListLine addValue(int index, int value) { 73 | return addValue(index, (long) value); 74 | 75 | } 76 | 77 | public ListLine addValue(int index, long value) { 78 | if (listLong == null) { 79 | listLong = new ArrayList<>(); 80 | } 81 | listLong.add(new CellKV(index, value)); 82 | changeIndex(index); 83 | return this; 84 | } 85 | 86 | public ListLine addValue(int index, double value) { 87 | if (listDouble == null) { 88 | listDouble = new ArrayList<>(); 89 | } 90 | changeIndex(index); 91 | listDouble.add(new CellKV(index, value)); 92 | return this; 93 | } 94 | 95 | 96 | 97 | public ListLine addValue(int index, String value) { 98 | if (listStr == null) { 99 | listStr = new ArrayList<>(); 100 | } 101 | listStr.add(new CellKV(index, value)); 102 | changeIndex(index); 103 | return this; 104 | } 105 | 106 | public ListLine addValue(int index, boolean value) { 107 | if (listBoolean == null) { 108 | listBoolean = new ArrayList<>(); 109 | } 110 | listBoolean.add(new CellKV(index, value)); 111 | changeIndex(index); 112 | return this; 113 | } 114 | 115 | public ListLine addValue(int index, Date value) { 116 | if (listDate == null) { 117 | listDate = new ArrayList<>(); 118 | } 119 | listDate.add(new CellKV(index, value)); 120 | changeIndex(index); 121 | return this; 122 | } 123 | 124 | 125 | private void changeIndex(int index) { 126 | if (index > maxIndex) { 127 | maxIndex = index; 128 | } 129 | if (minIndex == -1) { 130 | minIndex = index; 131 | } else { 132 | if (index < minIndex) { 133 | minIndex = index; 134 | } 135 | } 136 | } 137 | 138 | public int getMinIndex() { 139 | return minIndex; 140 | } 141 | 142 | public int getMaxIndex() { 143 | return maxIndex; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/core/BingExcel.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.core; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.OutputStream; 8 | import java.sql.SQLException; 9 | import java.util.List; 10 | 11 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 12 | import org.apache.poi.openxml4j.exceptions.OpenXML4JException; 13 | import org.xml.sax.SAXException; 14 | 15 | import com.bing.excel.converter.FieldValueConverter; 16 | import com.bing.excel.core.impl.BingExcelImpl; 17 | import com.bing.excel.core.impl.BingExcelImpl.SheetExcel; 18 | 19 | 20 | /** 21 | * 操作excel的类,需要poi3.13的jar包
22 | * maven地址,目前仅支持03版本 23 | *

24 | * <dependency>
25 | *  <groupId>org.apache.poi</groupId>
26 | *  <artifactId>poi</artifactId>
27 | *   <version>3.8</version>
28 | * </dependency> 29 | *

30 | * 31 | * @author shizhongtao 32 | * 33 | * 2015 2015-4-24 下午5:49:55 34 | */ 35 | public interface BingExcel { 36 | 37 | /** 38 | *

39 | * Title: readFileToList</p> 40 | *

41 | * Description:读取excel 的第一个sheet页到list</p> 42 | * 43 | * @param file excel对应的文件 44 | * @param clazz 要转换类型的class对象 45 | * @param startRowNum 从第几行开始读取 46 | */ 47 | BingExcelImpl.SheetVo readFile(File file, Class clazz, int startRowNum) 48 | throws Exception; 49 | 50 | /** 51 | * 根据condition条件读取相应的sheet到list对象 52 | */ 53 | BingExcelImpl.SheetVo readFile(File file, ReaderCondition condition) throws Exception; 54 | 55 | 56 | /** 57 | * 读取所condition 对应 sheet表格,到list 58 | * 59 | * @param conditions 每个表格对应的condition,注:对于返回的条数,取conditions中 endNum的最小值 60 | * @return sheetVo的list对象,如果没有符合conditions的结果,返回empetyList对象 61 | */ 62 | List readFileToList(File file, ReaderCondition[] conditions) 63 | throws Exception; 64 | 65 | 66 | BingExcelImpl.SheetVo readStream(InputStream stream, ReaderCondition condition) 67 | throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException; 68 | 69 | /** 70 | * read sheet witch index equal 0 71 | */ 72 | BingExcelImpl.SheetVo readStream(InputStream stream, Class clazz, int startRowNum) 73 | throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException; 74 | 75 | /** 76 | * read sheets 77 | */ 78 | List readStreamToList(InputStream stream, ReaderCondition[] condition) 79 | throws InvalidFormatException, IOException, SQLException, OpenXML4JException, SAXException; 80 | 81 | /** 82 | * 输出model集合到excel 文件。 83 | * 84 | * @param iterables 要输出到文件的集合对象, 85 | * @param file 文件对象 86 | */ 87 | void writeExcel(File file, Iterable... iterables) throws FileNotFoundException; 88 | 89 | void writeOldExcel(File file, Iterable... iterables) throws FileNotFoundException; 90 | 91 | /** 92 | * 输出model集合到excel 文件。 93 | * 94 | * @param path 文件路径 95 | */ 96 | void writeExcel(String path, Iterable... iterables); 97 | 98 | /** 99 | * 写出xls格式的excel文件 100 | */ 101 | void writeOldExcel(String path, Iterable... iterables); 102 | 103 | /** 104 | * 写出xls格式的excel到输出流 105 | */ 106 | void writeExcel(OutputStream stream, Iterable... iterables); 107 | 108 | void writeOldExcel(OutputStream stream, Iterable... iterables); 109 | 110 | void writeCSV(String path, Iterable iterable) throws IOException; 111 | 112 | void writeCSV(OutputStream os, Iterable iterable) throws IOException; 113 | 114 | /** 115 | * 写出指定分隔符、指定是否写header的文件到输出流 116 | * 117 | * @param os 输出流 118 | * @param iterable 带转换的对象 119 | * @param delimiter 分隔符 120 | * @param isWithHeader 是否写入header行 121 | * @param isWithBOM 是否带BOM 122 | */ 123 | void writeCSV(OutputStream os, Iterable iterable, char delimiter, boolean isWithHeader, 124 | boolean isWithBOM) throws IOException; 125 | 126 | void modelName(Class clazz, String alias); 127 | 128 | void fieldConverter(Class clazz, String filedName, int index, String alias, 129 | FieldValueConverter converter); 130 | 131 | /** 132 | * 写出多sheet页的xls格式的excel文件暂时只支持xls格式,后续支持csv格式 133 | * 134 | * @param 135 | * 136 | * @param path 137 | * @param list 138 | */ 139 | void writeSheetsExcel(String path, SheetExcel... sheetExcels); 140 | } 141 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTestSheetExcel.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import java.io.IOException; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang3.RandomStringUtils; 8 | import org.junit.Before; 9 | import org.junit.Test; 10 | 11 | import com.bing.excel.annotation.CellConfig; 12 | import com.bing.excel.annotation.OutAlias; 13 | import com.bing.excel.core.BingExcel; 14 | import com.bing.excel.core.BingExcelBuilder; 15 | import com.bing.excel.core.impl.BingExcelImpl.SheetExcel; 16 | import com.google.common.base.MoreObjects; 17 | import com.google.common.collect.Lists; 18 | 19 | /** 20 | * @author liluzhong 21 | * @date 2019/03/07 22 | * 23 | */ 24 | public class WriteTestSheetExcel { 25 | BingExcel bing; 26 | 27 | @Before 28 | public void before() { 29 | bing = BingExcelBuilder.toBuilder().builder(); 30 | } 31 | 32 | @Test 33 | public void testWrite() throws IOException { 34 | List sheetList = new ArrayList<>(); 35 | SheetExcel sheetExcels1 = new SheetExcel(); 36 | 37 | // 造数据 List 38 | SheetExcel seExcel1 = new SheetExcel(); 39 | List list = Lists.newArrayList(); 40 | list.add(new Person(23, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 41 | list.add(new Person(24, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 42 | list.add(new Person(25, RandomStringUtils.randomAlphanumeric(4), Math.random() * 1000)); 43 | seExcel1.setSheetName("org"); 44 | seExcel1.setList(list); 45 | 46 | SheetExcel seExcel2 = new SheetExcel(); // 造数据 List 47 | List list1 = Lists.newArrayList(); 48 | 49 | list1.add(new Student(RandomStringUtils.randomAlphanumeric(4), 50 | RandomStringUtils.randomAlphanumeric(4), RandomStringUtils.randomAlphanumeric(4))); 51 | list1.add(new Student(RandomStringUtils.randomAlphanumeric(4), 52 | RandomStringUtils.randomAlphanumeric(4), RandomStringUtils.randomAlphanumeric(4))); 53 | list1.add(new Student(RandomStringUtils.randomAlphanumeric(4), 54 | RandomStringUtils.randomAlphanumeric(4), RandomStringUtils.randomAlphanumeric(4))); 55 | 56 | seExcel2.setSheetName("business"); 57 | seExcel2.setList(list1); 58 | 59 | 60 | // bing.writeSheetsExcel("C:\\Users\\shi\\workspace/sheets.xlsx", seExcel1, seExcel2); 61 | 62 | bing.writeSheetsExcel("/Users/shi/workspace/aa/adb.xlsx", seExcel2,seExcel1); 63 | // bing.writeCSV("/Users/shi/workspace/aa/adb.csv", list); 64 | } 65 | 66 | @OutAlias("xiaoshou") 67 | public static class Person { 68 | 69 | public Person(int age, String name, Double salary) { 70 | super(); 71 | this.age = age; 72 | this.name = name; 73 | this.salary = salary; 74 | } 75 | 76 | public Person() { 77 | super(); 78 | } 79 | 80 | 81 | @CellConfig(index = 0) 82 | private String name; 83 | @CellConfig(index = 1, aliasName = "年龄") 84 | private int age; 85 | @CellConfig(index = 2) 86 | private Double salary; 87 | 88 | public Person getFriends() { 89 | return friends; 90 | } 91 | 92 | public void setFriends(Person friends) { 93 | this.friends = friends; 94 | } 95 | 96 | private Person friends; 97 | 98 | private transient boolean testProperty = false; 99 | 100 | public String getName() { 101 | return name; 102 | } 103 | 104 | public void setName(String name) { 105 | this.name = name; 106 | } 107 | 108 | public int getAge() { 109 | return age; 110 | } 111 | 112 | public Double getSalary() { 113 | return salary; 114 | } 115 | 116 | @Override 117 | public String toString() { 118 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues().add("name", name) 119 | .add("age", age).add("salary", salary).toString(); 120 | } 121 | } 122 | @OutAlias("测试名字") 123 | public static class Student { 124 | @CellConfig(index = 0) 125 | private String schoolName; 126 | @CellConfig(index = 1) 127 | private String className; 128 | @CellConfig(index = 2) 129 | private String name; 130 | 131 | public Student() {} 132 | 133 | public Student(String schoolName, String className, String name) { 134 | this.schoolName = schoolName; 135 | this.className = className; 136 | this.name = name; 137 | } 138 | 139 | @Override 140 | public String toString() { 141 | return MoreObjects.toStringHelper(this).omitNullValues().add("schoolName", schoolName) 142 | .add("className", className).add("name", name).toString(); 143 | } 144 | } 145 | 146 | } 147 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest5.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import com.bing.excel.annotation.BingConvertor; 4 | import com.bing.excel.converter.AbstractFieldConvertor; 5 | import com.bing.excel.core.BingExcel; 6 | import com.bing.excel.core.BingExcelBuilder; 7 | import com.bing.excel.core.handler.ConverterHandler; 8 | import com.bing.excel.vo.OutValue; 9 | import com.bing.excel.vo.OutValue.OutType; 10 | import com.bing.utils.StringParseUtil; 11 | import com.chinamobile.excel.WriteTest2.Person; 12 | import com.google.common.base.MoreObjects; 13 | import com.bing.excel.annotation.CellConfig; 14 | import com.bing.excel.annotation.OutAlias; 15 | import com.bing.excel.core.BingExcelEvent; 16 | import com.bing.excel.core.BingExcelEventBuilder; 17 | import com.bing.excel.core.rw.BingWriterHandler; 18 | 19 | import com.google.common.collect.Lists; 20 | import java.lang.reflect.Type; 21 | import java.text.ParseException; 22 | import java.util.Date; 23 | import java.util.List; 24 | import org.apache.commons.lang3.RandomStringUtils; 25 | import org.apache.commons.lang3.StringUtils; 26 | import org.junit.Before; 27 | import org.junit.Test; 28 | 29 | /** 30 | * @author shizhongtao 31 | */ 32 | public class WriteTest5 { 33 | BingExcel bing; 34 | 35 | @Before 36 | public void before() { 37 | bing = BingExcelBuilder.builderInstance(); 38 | } 39 | 40 | @Test 41 | public void testWrite() { 42 | List list= Lists.newArrayList(); 43 | List listFriend= Lists.newArrayList(); 44 | 45 | Person person = new Person(23, "wori",3.45); 46 | Student obj1 = new Student("高中", "friends1","3.45"); 47 | Student obj2 = new Student("初中", "friends2","3.45"); 48 | listFriend.add(obj1); 49 | listFriend.add(obj2); 50 | person.setFriends(listFriend); 51 | list.add(person); 52 | bing.writeExcel("/Users/shi/workspace/student.xlsx",list); 53 | 54 | 55 | } 56 | 57 | @OutAlias("xiaoshou") 58 | public static class Person { 59 | 60 | public Person(int age, String name, Double salary) { 61 | super(); 62 | this.age = age; 63 | this.name = name; 64 | this.salary = salary; 65 | } 66 | 67 | public Person() { 68 | super(); 69 | } 70 | 71 | @CellConfig(index = 1, aliasName = "年龄") 72 | private int age; 73 | @CellConfig(index = 0) 74 | private String name; 75 | @CellConfig(index = 3) 76 | private Double salary; 77 | @CellConfig(index = 2) 78 | @BingConvertor(MyListConverter.class) 79 | private List friends; 80 | 81 | public List getFriends() { 82 | return friends; 83 | } 84 | 85 | public void setFriends(List friends) { 86 | this.friends = friends; 87 | } 88 | 89 | private transient boolean testProperty = false; 90 | 91 | public String getName() { 92 | return name; 93 | } 94 | 95 | public void setName(String name) { 96 | this.name = name; 97 | } 98 | 99 | public int getAge() { 100 | return age; 101 | } 102 | 103 | public Double getSalary() { 104 | return salary; 105 | } 106 | 107 | public String toString() { 108 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 109 | .add("name", name).add("age", age).add("salary", salary) 110 | .toString(); 111 | } 112 | } 113 | 114 | public static class Student { 115 | @CellConfig(index = 0) 116 | private String schoolName; 117 | @CellConfig(index = 1) 118 | private String className; 119 | @CellConfig(index = 2) 120 | private String name; 121 | 122 | public Student() { 123 | } 124 | 125 | public Student(String schoolName, String className, String name) { 126 | this.schoolName = schoolName; 127 | this.className = className; 128 | this.name = name; 129 | } 130 | 131 | @Override 132 | public String toString() { 133 | return MoreObjects.toStringHelper(this).omitNullValues() 134 | .add("schoolName", schoolName) 135 | .add("className", className) 136 | .add("name", name) 137 | .toString(); 138 | } 139 | } 140 | 141 | 142 | public static class MyListConverter extends AbstractFieldConvertor { 143 | 144 | @Override 145 | public boolean canConvert(Class clz) { 146 | 147 | return List.class.isAssignableFrom(clz); 148 | } 149 | 150 | @Override 151 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 152 | if (source==null) { 153 | return null; 154 | } 155 | 156 | return new OutValue(OutType.STRING,source.toString()); 157 | 158 | } 159 | 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/other/MyTest.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.other; 2 | 3 | import java.io.File; 4 | import java.io.FileOutputStream; 5 | import java.io.IOException; 6 | import java.util.HashMap; 7 | import java.util.Map; 8 | 9 | import org.apache.poi.EncryptedDocumentException; 10 | import org.apache.poi.hssf.usermodel.HSSFWorkbook; 11 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 12 | import org.apache.poi.ss.usermodel.Cell; 13 | import org.apache.poi.ss.usermodel.CellStyle; 14 | import org.apache.poi.ss.usermodel.Font; 15 | import org.apache.poi.ss.usermodel.IndexedColors; 16 | import org.apache.poi.ss.usermodel.Row; 17 | import org.apache.poi.ss.usermodel.Sheet; 18 | import org.apache.poi.ss.usermodel.Workbook; 19 | import org.apache.poi.ss.util.CellRangeAddress; 20 | import org.apache.poi.ss.util.CellUtil; 21 | import org.apache.poi.xssf.usermodel.XSSFWorkbook; 22 | import org.junit.Test; 23 | 24 | public class MyTest { 25 | @Test 26 | public void testme() throws IOException { 27 | 28 | Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook(); 29 | 30 | Sheet sheet = wb.createSheet(); 31 | Row row = sheet.createRow((short) 2); 32 | row.setHeightInPoints(30); 33 | 34 | createCell(wb, row, (short) 0, CellStyle.ALIGN_CENTER, CellStyle.VERTICAL_BOTTOM); 35 | createCell(wb, row, (short) 1, CellStyle.ALIGN_CENTER_SELECTION, CellStyle.VERTICAL_BOTTOM); 36 | createCell(wb, row, (short) 2, CellStyle.ALIGN_FILL, CellStyle.VERTICAL_CENTER); 37 | createCell(wb, row, (short) 3, CellStyle.ALIGN_GENERAL, CellStyle.VERTICAL_CENTER); 38 | createCell(wb, row, (short) 4, CellStyle.ALIGN_JUSTIFY, CellStyle.VERTICAL_JUSTIFY); 39 | createCell(wb, row, (short) 5, CellStyle.ALIGN_LEFT, CellStyle.VERTICAL_TOP); 40 | createCell(wb, row, (short) 6, CellStyle.ALIGN_RIGHT, CellStyle.VERTICAL_TOP); 41 | // Write the output to a file 42 | 43 | FileOutputStream fileOut = new FileOutputStream("xssf-align.xlsx"); 44 | wb.write(fileOut); 45 | 46 | fileOut.close(); 47 | } 48 | /** 49 | * Creates a cell and aligns it a certain way. 50 | * 51 | * @param wb the workbook 52 | * @param row the row to create the cell in 53 | * @param column the column number to create the cell in 54 | * @param halign the horizontal alignment for the cell. 55 | */ 56 | private void createCell(Workbook wb, Row row, short column, short halign, short valign) { 57 | Cell cell = row.createCell(column); 58 | cell.setCellValue("Align It"); 59 | CellStyle cellStyle = wb.createCellStyle(); 60 | cellStyle.setAlignment(halign); 61 | cellStyle.setVerticalAlignment(valign); 62 | cell.setCellStyle(cellStyle); 63 | } 64 | 65 | @Test 66 | public void test2() throws IOException{ 67 | Workbook wb = new HSSFWorkbook(); 68 | Sheet sheet = wb.createSheet("new sheet"); 69 | 70 | // Create a row and put some cells in it. Rows are 0 based. 71 | Row row = sheet.createRow(1); 72 | 73 | // Create a cell and put a value in it. 74 | 75 | 76 | // Style the cell with borders all around. 77 | CellStyle style = wb.createCellStyle(); 78 | 79 | // style.setFillBackgroundColor(IndexedColors.AUTOMATIC.getIndex()); 80 | style.setFillPattern(CellStyle.SOLID_FOREGROUND); 81 | style.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.index); 82 | 83 | Font font = wb.createFont(); 84 | font.setFontHeightInPoints((short)24); 85 | font.setFontName("Courier New"); 86 | font.setItalic(true); 87 | font.setStrikeout(true); 88 | style.setFont(font); 89 | CellUtil.createCell(row, 1, "nihao",style); 90 | //style.setFont(font); 91 | // Write the output to a file 92 | FileOutputStream fileOut = new FileOutputStream("workbook.xls"); 93 | wb.write(fileOut); 94 | fileOut.close(); 95 | } 96 | private Map map=new HashMap(); 97 | @Test 98 | public void before(){ 99 | map.put("a", "aa"); 100 | } 101 | 102 | @Test 103 | public void testLong() throws EncryptedDocumentException, InvalidFormatException, IOException{ 104 | Workbook wb = new HSSFWorkbook(); 105 | Sheet sheet = wb.createSheet("new sheet"); 106 | 107 | Row row = sheet.createRow((short) 1); 108 | Cell cell = row.createCell((short) 1); 109 | cell.setCellValue("This is a aoptest of merging"); 110 | 111 | sheet.addMergedRegion(new CellRangeAddress( 112 | 1, //first row (0-based) 113 | 1, //last row (0-based) 114 | 1, //first column (0-based) 115 | 2 //last column (0-based) 116 | )); 117 | 118 | // Write the output to a file 119 | FileOutputStream fileOut = new FileOutputStream(new File("E:/aoptest/gzb.xls")); 120 | wb.write(fileOut); 121 | fileOut.close(); 122 | 123 | } 124 | } 125 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/sax/ExcelReadOnlySharedStringsTable.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader.sax; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | 8 | import javax.xml.parsers.ParserConfigurationException; 9 | 10 | import org.apache.poi.openxml4j.opc.OPCPackage; 11 | import org.apache.poi.openxml4j.opc.PackagePart; 12 | import org.apache.poi.openxml4j.opc.PackageRelationship; 13 | import org.apache.poi.util.SAXHelper; 14 | import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable; 15 | import org.xml.sax.Attributes; 16 | import org.xml.sax.InputSource; 17 | import org.xml.sax.SAXException; 18 | import org.xml.sax.XMLReader; 19 | 20 | /** 21 | * @author shizhongtao 22 | * 23 | * date 2016-1-26 24 | * Description: 解决读取mac上xlsx结尾的excel文件读取中文问题 25 | */ 26 | public class ExcelReadOnlySharedStringsTable extends ReadOnlySharedStringsTable { 27 | 28 | public ExcelReadOnlySharedStringsTable(OPCPackage pkg) throws IOException, 29 | SAXException { 30 | super(pkg); 31 | 32 | } 33 | 34 | public ExcelReadOnlySharedStringsTable(PackagePart part, 35 | PackageRelationship rel_ignored) throws IOException, SAXException { 36 | super(part, rel_ignored); 37 | 38 | } 39 | 40 | /** 41 | * An integer representing the total count of strings in the workbook. This 42 | * count does not include any numbers, it counts only the total of text 43 | * strings in the workbook. 44 | */ 45 | private int count; 46 | 47 | /** 48 | * An integer representing the total count of unique strings in the Shared 49 | * String Table. A string is unique even if it is a copy of another string, 50 | * but has different formatting applied at the character level. 51 | */ 52 | private int uniqueCount; 53 | 54 | /** 55 | * The shared strings table. 56 | */ 57 | private List strings; 58 | 59 | /** 60 | * Read this shared strings table from an XML file. 61 | * 62 | * @param is 63 | * The input stream containing the XML document. 64 | * @throws IOException 65 | * if an error occurs while reading. 66 | * @throws SAXException 67 | */ 68 | public void readFrom(InputStream is) throws IOException, SAXException { 69 | if (is.available() > 0) { 70 | InputSource sheetSource = new InputSource(is); 71 | try { 72 | XMLReader sheetParser = SAXHelper.newXMLReader(); 73 | sheetParser.setContentHandler(this); 74 | sheetParser.parse(sheetSource); 75 | } catch (ParserConfigurationException e) { 76 | throw new RuntimeException("SAX parser appears to be broken - " 77 | + e.getMessage()); 78 | } 79 | } 80 | } 81 | 82 | /** 83 | * Return an integer representing the total count of strings in the 84 | * workbook. This count does not include any numbers, it counts only the 85 | * total of text strings in the workbook. 86 | * 87 | * @return the total count of strings in the workbook 88 | */ 89 | public int getCount() { 90 | return this.count; 91 | } 92 | 93 | /** 94 | * Returns an integer representing the total count of unique strings in the 95 | * Shared String Table. A string is unique even if it is a copy of another 96 | * string, but has different formatting applied at the character level. 97 | * 98 | * @return the total count of unique strings in the workbook 99 | */ 100 | public int getUniqueCount() { 101 | return this.uniqueCount; 102 | } 103 | 104 | /** 105 | * Return the string at a given index. Formatting is ignored. 106 | * 107 | * @param idx 108 | * index of item to return. 109 | * @return the item at the specified position in this Shared String table. 110 | */ 111 | public String getEntryAt(int idx) { 112 | return strings.get(idx); 113 | } 114 | 115 | public List getItems() { 116 | return strings; 117 | } 118 | 119 | // // ContentHandler methods //// 120 | 121 | private StringBuffer characters; 122 | private boolean rPhIsOpen = false; 123 | private boolean tIsOpen; 124 | 125 | @Override 126 | public void startElement(String uri, String localName, String name, 127 | Attributes attributes) throws SAXException { 128 | if ("sst".equals(name)) { 129 | String count = attributes.getValue("count"); 130 | if (count != null) 131 | this.count = Integer.parseInt(count); 132 | String uniqueCount = attributes.getValue("uniqueCount"); 133 | if (uniqueCount != null) 134 | this.uniqueCount = Integer.parseInt(uniqueCount); 135 | 136 | this.strings = new ArrayList(this.uniqueCount); 137 | 138 | characters = new StringBuffer(); 139 | } else if ("si".equals(name)) { 140 | characters.setLength(0); 141 | } else if ("t".equals(name)) { 142 | tIsOpen = true; 143 | } else if ("rPh".equals(name)) { 144 | rPhIsOpen = true; 145 | } 146 | } 147 | 148 | @Override 149 | public void endElement(String uri, String localName, String name) 150 | throws SAXException { 151 | if ("si".equals(name)) { 152 | strings.add(characters.toString()); 153 | } else if ("t".equals(name)) { 154 | tIsOpen = false; 155 | } else if ("rPh".equals(name)) { 156 | rPhIsOpen = false; 157 | } 158 | } 159 | 160 | @Override 161 | public void characters(char[] ch, int start, int length) 162 | throws SAXException { 163 | if (tIsOpen) { 164 | if (!rPhIsOpen) { 165 | characters.append(ch, start, length); 166 | } 167 | } 168 | } 169 | 170 | } 171 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/ExcelReaderFactory.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader; 2 | 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.io.PushbackInputStream; 8 | import java.sql.SQLException; 9 | 10 | import org.apache.poi.POIXMLDocument; 11 | import org.apache.poi.openxml4j.exceptions.InvalidFormatException; 12 | import org.apache.poi.openxml4j.opc.OPCPackage; 13 | import org.apache.poi.openxml4j.opc.PackageAccess; 14 | import org.apache.poi.poifs.filesystem.OfficeXmlFileException; 15 | import org.apache.poi.poifs.filesystem.POIFSFileSystem; 16 | import org.apache.poi.util.IOUtils; 17 | 18 | import com.bing.excel.reader.hssf.DefaultHSSFHandler; 19 | import com.bing.excel.reader.sax.DefaultXSSFSaxHandler; 20 | 21 | /** 22 | * @author shizhongtao 23 | * 24 | * date 2016-3-1 25 | * Description: 26 | */ 27 | public class ExcelReaderFactory { 28 | /** 29 | * @param file 30 | * @param excelReadListener 31 | * @param ignoreNumFormat 是否忽略数据格式 (default=false,按照格式读取) 32 | * @return 33 | * @throws Exception 34 | */ 35 | public static ReadHandler create(File file, ExcelReadListener excelReadListener, 36 | boolean ignoreNumFormat) throws Exception { 37 | if (!file.exists()) { 38 | throw new FileNotFoundException(file.toString()); 39 | } 40 | try { 41 | POIFSFileSystem fs = new POIFSFileSystem(file); 42 | return create(fs, excelReadListener, ignoreNumFormat); 43 | } catch (OfficeXmlFileException e) { 44 | OPCPackage pkg = OPCPackage.open(file, PackageAccess.READ); 45 | try { 46 | return create(pkg, excelReadListener, ignoreNumFormat); 47 | } catch (IllegalArgumentException | IOException e1) { 48 | pkg.revert(); 49 | throw e1; 50 | } 51 | } 52 | 53 | } 54 | 55 | /** 56 | * @param file 57 | * @param excelReader 58 | * @return 59 | * @throws Exception 60 | */ 61 | public static ReadHandler create(File file, ExcelReadListener excelReader) 62 | throws Exception { 63 | return create(file, excelReader, false); 64 | 65 | } 66 | 67 | 68 | /** 69 | * @param inp 70 | * @param excelReader 71 | * @param maxReturnLines null 不限制, 72 | * @return 73 | * @throws InvalidFormatException 74 | * @throws IOException 75 | * @throws SQLException 76 | */ 77 | public static ReadHandler create(InputStream inp, 78 | ExcelReadListener excelReader) throws InvalidFormatException, IOException, SQLException { 79 | return create(inp, excelReader, false); 80 | } 81 | /** 82 | * @param inp 83 | * @param excelReader 84 | * @param ignoreNumFormat 是否忽略数据格式 (default=false,按照格式读取) 85 | * @return jie 86 | * @throws InvalidFormatException 87 | * @throws IOException 88 | * @throws SQLException 89 | */ 90 | public static ReadHandler create(InputStream inp, 91 | ExcelReadListener excelReader, boolean ignoreNumFormat) 92 | throws InvalidFormatException, IOException, SQLException { 93 | // If clearly doesn't do mark/reset, wrap up 94 | if (! inp.markSupported()) { 95 | inp = new PushbackInputStream(inp, 8); 96 | } 97 | 98 | // Ensure that there is at least some data there 99 | byte[] header8 = IOUtils.peekFirst8Bytes(inp); 100 | 101 | // Try to create 102 | if (POIFSFileSystem.hasPOIFSHeader(header8)) { 103 | POIFSFileSystem fs = new POIFSFileSystem(inp); 104 | return create(fs, excelReader, ignoreNumFormat); 105 | } 106 | if (POIXMLDocument.hasOOXMLHeader(inp)) { 107 | OPCPackage pkg = OPCPackage.open(inp); 108 | return create(pkg, excelReader, ignoreNumFormat); 109 | } 110 | throw new InvalidFormatException("Your InputStream was neither an OLE2 stream, nor an OOXML stream"); 111 | 112 | 113 | } 114 | 115 | /** 116 | * @param pkg 117 | * @param excelReader 118 | * @return 119 | * @throws SQLException 120 | * @throws InvalidFormatException 121 | * @throws IOException 122 | */ 123 | public static ReadHandler create(OPCPackage pkg, 124 | ExcelReadListener excelReader) throws SQLException, 125 | InvalidFormatException, IOException { 126 | return create(pkg, excelReader, false); 127 | } 128 | 129 | /* 130 | * public static SaxHandler create(OPCPackage pkg,ExcelReadListener 131 | * excelReadListener,Integer maxReturnLines) throws SQLException, 132 | * InvalidFormatException, IOException{ return 133 | * create(pkg,excelReadListener,false,maxReturnLines); } public static SaxHandler 134 | * create(OPCPackage pkg,ExcelReadListener excelReadListener,boolean 135 | * ignoreNumFormat) throws SQLException, InvalidFormatException, 136 | * IOException{ return create(pkg,excelReadListener,ignoreNumFormat,null); } 137 | */ 138 | public static ReadHandler create(OPCPackage pkg, 139 | ExcelReadListener excelReadListener, boolean ignoreNumFormat) throws SQLException, 140 | InvalidFormatException, IOException { 141 | DefaultXSSFSaxHandler handler = new DefaultXSSFSaxHandler(pkg, 142 | excelReadListener, ignoreNumFormat); 143 | 144 | return handler; 145 | } 146 | 147 | public static ReadHandler create(POIFSFileSystem fs, 148 | ExcelReadListener excelReader) throws SQLException { 149 | return create(fs, excelReader, false); 150 | } 151 | 152 | /* 153 | * public static SaxHandler create(POIFSFileSystem fs,ExcelReadListener 154 | * excelReader,Integer maxReturnLines) throws SQLException{ return 155 | * create(fs,excelReader,false,maxReturnLines); } public static SaxHandler 156 | * create(POIFSFileSystem fs,ExcelReadListener excelReader,boolean 157 | * ignoreNumFormat) throws SQLException{ return 158 | * create(fs,excelReader,ignoreNumFormat,null); } 159 | */ 160 | public static ReadHandler create(POIFSFileSystem fs, 161 | ExcelReadListener excelReader, boolean ignoreNumFormat) throws SQLException { 162 | DefaultHSSFHandler handler = new DefaultHSSFHandler(fs, excelReader, 163 | ignoreNumFormat); 164 | 165 | return handler; 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/usermodel/ExcelHSSFDataFormat.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader.usermodel; 2 | 3 | /* ==================================================================== 4 | Licensed to the Apache Software Foundation (ASF) under one or more 5 | contributor license agreements. See the NOTICE file distributed with 6 | this work for additional information regarding copyright ownership. 7 | The ASF licenses this file to You under the Apache License, Version 2.0 8 | (the "License"); you may not use this file except in compliance with 9 | the License. You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | ==================================================================== */ 19 | import java.util.Arrays; 20 | import java.util.Iterator; 21 | import java.util.List; 22 | import java.util.Locale; 23 | import java.util.Vector; 24 | 25 | import org.apache.poi.hssf.model.InternalWorkbook; 26 | import org.apache.poi.hssf.record.FormatRecord; 27 | import org.apache.poi.ss.usermodel.DataFormat; 28 | 29 | /** 30 | * Identifies both built-in and user defined formats within a workbook.

31 | * See {@link ExcelBuiltinFormats} for a list of supported built-in formats.

32 | * 33 | * International Formats
34 | * Since version 2003 Excel has supported international formats. These are denoted 35 | * with a prefix "[$-xxx]" (where xxx is a 1-7 digit hexadecimal number). 36 | * See the Microsoft article 37 | * 38 | * Creating international number formats 39 | * for more details on these codes. 40 | */ 41 | public final class ExcelHSSFDataFormat implements DataFormat { 42 | private static final String[] _builtinFormats = ExcelBuiltinFormats.getAll(); 43 | 44 | private final Vector _formats = new Vector(); 45 | private final InternalWorkbook _workbook; 46 | private boolean _movedBuiltins = false; // Flag to see if need to 47 | // check the built in list 48 | // or if the regular list 49 | // has all entries. 50 | 51 | /** 52 | * Constructs a new data formatter. It takes a workbook to have 53 | * access to the workbooks format records. 54 | * @param workbook the workbook the formats are tied to. 55 | */ 56 | ExcelHSSFDataFormat(InternalWorkbook workbook) { 57 | _workbook = workbook; 58 | 59 | Iterator i = workbook.getFormats().iterator(); 60 | while (i.hasNext()) { 61 | FormatRecord r = i.next(); 62 | ensureFormatsSize(r.getIndexCode()); 63 | _formats.set(r.getIndexCode(), r.getFormatString()); 64 | } 65 | } 66 | 67 | public static List getBuiltinFormats() { 68 | return Arrays.asList(_builtinFormats); 69 | } 70 | 71 | /** 72 | * get the format index that matches the given format string

73 | * Automatically converts "text" to excel's format string to represent text. 74 | * @param format string matching a built in format 75 | * @return index of format or -1 if undefined. 76 | */ 77 | public static short getBuiltinFormat(String format) { 78 | return (short) ExcelBuiltinFormats.getBuiltinFormat(format); 79 | } 80 | 81 | /** 82 | * Get the format index that matches the given format 83 | * string, creating a new format entry if required. 84 | * Aliases text to the proper format as required. 85 | * @param pFormat string matching a built in format 86 | * @return index of format. 87 | */ 88 | public short getFormat(String pFormat) { 89 | // Normalise the format string 90 | String format; 91 | if (pFormat.toUpperCase(Locale.ROOT).equals("TEXT")) { 92 | format = "@"; 93 | } else { 94 | format = pFormat; 95 | } 96 | 97 | // Merge in the built in formats if we haven't already 98 | if (!_movedBuiltins) { 99 | for (int i=0; i<_builtinFormats.length; i++) { 100 | ensureFormatsSize(i); 101 | if (_formats.get(i) == null) { 102 | _formats.set(i, _builtinFormats[i]); 103 | } else { 104 | // The workbook overrides this default format 105 | } 106 | } 107 | _movedBuiltins = true; 108 | } 109 | 110 | // See if we can find it 111 | for(int i=0; i<_formats.size(); i++) { 112 | if(format.equals(_formats.get(i))) { 113 | return (short)i; 114 | } 115 | } 116 | 117 | // We can't find it, so add it as a new one 118 | short index = _workbook.getFormat(format, true); 119 | ensureFormatsSize(index); 120 | _formats.set(index, format); 121 | return index; 122 | } 123 | 124 | /** 125 | * get the format string that matches the given format index 126 | * @param index of a format 127 | * @return string represented at index of format or null if there is not a format at that index 128 | */ 129 | public String getFormat(short index) { 130 | if (_movedBuiltins) { 131 | return _formats.get(index); 132 | } 133 | 134 | if(index == -1) { 135 | // YK: formatIndex can be -1, for example, for cell in column Y in aoptest-data/spreadsheet/45322.xls 136 | // return null for those 137 | return null; 138 | } 139 | 140 | String fmt = _formats.size() > index ? _formats.get(index) : null; 141 | if (_builtinFormats.length > index && _builtinFormats[index] != null) { 142 | // It's in the built in range 143 | if (fmt != null) { 144 | // It's been overriden, use that value 145 | return fmt; 146 | } else { 147 | // Standard built in format 148 | return _builtinFormats[index]; 149 | } 150 | } 151 | return fmt; 152 | } 153 | 154 | /** 155 | * get the format string that matches the given format index 156 | * @param index of a built in format 157 | * @return string represented at index of format or null if there is not a builtin format at that index 158 | */ 159 | public static String getBuiltinFormat(short index) { 160 | return ExcelBuiltinFormats.getBuiltinFormat(index); 161 | } 162 | 163 | /** 164 | * get the number of built-in and reserved builtinFormats 165 | * @return number of built-in and reserved builtinFormats 166 | */ 167 | public static int getNumberOfBuiltinBuiltinFormats() { 168 | return _builtinFormats.length; 169 | } 170 | 171 | /** 172 | * Ensures that the formats list can hold entries 173 | * up to and including the entry with this index 174 | */ 175 | private void ensureFormatsSize(int index) { 176 | if(_formats.size() <= index) { 177 | _formats.setSize(index+1); 178 | } 179 | } 180 | } 181 | -------------------------------------------------------------------------------- /excel/src/test/java/com/chinamobile/excel/WriteTest6.java: -------------------------------------------------------------------------------- 1 | package com.chinamobile.excel; 2 | 3 | import com.bing.excel.annotation.CellConfig; 4 | import com.bing.excel.annotation.OutAlias; 5 | import com.bing.excel.converter.AbstractFieldConvertor; 6 | import com.bing.excel.core.BingExcel; 7 | import com.bing.excel.core.BingExcelBuilder; 8 | import com.bing.excel.core.handler.ConverterHandler; 9 | import com.bing.excel.vo.OutValue; 10 | import com.bing.excel.vo.OutValue.OutType; 11 | import com.google.common.base.MoreObjects; 12 | import com.google.common.collect.Lists; 13 | import java.io.ByteArrayOutputStream; 14 | import java.io.File; 15 | import java.io.FileOutputStream; 16 | import java.io.IOException; 17 | import java.util.List; 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | 21 | /** 22 | * @author shizhongtao 23 | */ 24 | public class WriteTest6 { 25 | BingExcel bing; 26 | 27 | @Before 28 | public void before() { 29 | bing = BingExcelBuilder.toBuilder().addClassNameAlias(Person.class,"xuesheng1") 30 | .addFieldConversionMapper(Person.class,"name",0) 31 | .addFieldConversionMapper(Person.class,"age",1,"年龄").build(); 32 | } 33 | 34 | @Test 35 | public void testWrite() throws IOException { 36 | List list= Lists.newArrayList(); 37 | 38 | Person person = new Person(23, "wori",2.0); 39 | Person person2 = new Person(20, "lily",13.5); 40 | list.add(person); 41 | list.add(person2); 42 | list.add(person); 43 | 44 | //bing.writeExcel("/Users/shi/workspace/gaoxinqu/student.xlsx",list); 45 | bing.writeCSV("/Users/shi/workspace/gaoxinqu/student.csv",list); 46 | 47 | 48 | } 49 | 50 | @Test 51 | public void csvWrite_semiColon_noHead() throws IOException { 52 | BingExcel bingExcel = BingExcelBuilder.toBuilder().build(); 53 | ByteArrayOutputStream os = new ByteArrayOutputStream(); 54 | List list= Lists.newArrayList(); 55 | ApiUsedNumForCSV api1 = new ApiUsedNumForCSV(); 56 | api1.setDate("2018-10"); 57 | api1.setOwnerId("5632643255427352877312350"); 58 | api1.setTopicName("test1"); 59 | api1.setUsedNum(100000L); 60 | ApiUsedNumForCSV api2 = new ApiUsedNumForCSV(); 61 | api2.setDate("2018-10"); 62 | api2.setOwnerId("5632643255427352877312350"); 63 | api2.setTopicName("test2"); 64 | api2.setUsedNum(200000L); 65 | ApiUsedNumForCSV api3 = new ApiUsedNumForCSV(); 66 | api3.setDate("2018-10"); 67 | api3.setOwnerId("5632643255427352877312350"); 68 | api3.setTopicName("test3"); 69 | api3.setUsedNum(300000L); 70 | list.add(api1); 71 | list.add(api2); 72 | list.add(api3); 73 | 74 | bingExcel.writeCSV(os, list, ';', false, false); 75 | String result = new String(os.toByteArray()); 76 | System.out.println(result); 77 | 78 | File file = new File("E:\\test.csv"); 79 | FileOutputStream fileOutputStream = new FileOutputStream(file); 80 | fileOutputStream.write(os.toByteArray()); 81 | fileOutputStream.close(); 82 | } 83 | 84 | /** 85 | * Model类。生成CSV文件用。表示每月的api调用次数计量信息。 86 | * 87 | * @author chengxiangwang 88 | * @create 2018/10/30 89 | */ 90 | static class ApiUsedNumForCSV{ 91 | //Format: 2018-10 92 | @CellConfig(index = 0) 93 | private String month; 94 | @CellConfig(index = 1) 95 | private String topicName; 96 | @CellConfig(index = 2) 97 | private String ownerId; 98 | @CellConfig(index = 3) 99 | private Long apiUsedNum; 100 | 101 | public ApiUsedNumForCSV() { 102 | 103 | } 104 | public String getTopicName() { 105 | return topicName; 106 | } 107 | 108 | public void setTopicName(String topicName) { 109 | this.topicName = topicName; 110 | } 111 | 112 | public String getOwnerId() { 113 | return ownerId; 114 | } 115 | 116 | public void setOwnerId(String ownerId) { 117 | this.ownerId = ownerId; 118 | } 119 | 120 | public String getDate() { 121 | return month; 122 | } 123 | 124 | public void setDate(String month) { 125 | this.month = month; 126 | } 127 | 128 | public Long getUsedNum() { 129 | return apiUsedNum; 130 | } 131 | 132 | public void setUsedNum(Long apiUsedNum) { 133 | this.apiUsedNum = apiUsedNum; 134 | } 135 | } 136 | 137 | 138 | @OutAlias("xiaoshou1") 139 | public static class Person { 140 | 141 | private int age; 142 | private String name; 143 | @CellConfig(index = 2,aliasName = "工资") 144 | private Double salary; 145 | private List friends; 146 | 147 | public List getFriends() { 148 | return friends; 149 | } 150 | 151 | public void setFriends(List friends) { 152 | this.friends = friends; 153 | } 154 | 155 | private transient boolean testProperty = false; 156 | 157 | public String getName() { 158 | return name; 159 | } 160 | 161 | public void setName(String name) { 162 | this.name = name; 163 | } 164 | 165 | public int getAge() { 166 | return age; 167 | } 168 | 169 | public Double getSalary() { 170 | return salary; 171 | } 172 | public Person(int age, String name, Double salary) { 173 | super(); 174 | this.age = age; 175 | this.name = name; 176 | this.salary = salary; 177 | } 178 | public Person() { 179 | super(); 180 | } 181 | public String toString() { 182 | return MoreObjects.toStringHelper(this.getClass()).omitNullValues() 183 | .add("name", name).add("age", age).add("salary", salary) 184 | .toString(); 185 | } 186 | } 187 | 188 | public static class Student { 189 | @CellConfig(index = 0) 190 | private String schoolName; 191 | @CellConfig(index = 1) 192 | private String className; 193 | @CellConfig(index = 2) 194 | private String name; 195 | 196 | public Student() { 197 | } 198 | 199 | public Student(String schoolName, String className, String name) { 200 | this.schoolName = schoolName; 201 | this.className = className; 202 | this.name = name; 203 | } 204 | 205 | @Override 206 | public String toString() { 207 | return MoreObjects.toStringHelper(this).omitNullValues() 208 | .add("schoolName", schoolName) 209 | .add("className", className) 210 | .add("name", name) 211 | .toString(); 212 | } 213 | } 214 | 215 | 216 | public static class MyListConverter extends AbstractFieldConvertor { 217 | 218 | @Override 219 | public boolean canConvert(Class clz) { 220 | 221 | return List.class.isAssignableFrom(clz); 222 | } 223 | 224 | @Override 225 | public OutValue toObject(Object source, ConverterHandler converterHandler) { 226 | if (source==null) { 227 | return null; 228 | } 229 | 230 | return new OutValue(OutType.STRING,source.toString()); 231 | 232 | } 233 | 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/excel/reader/hssf/ExcelFormatTrackingHSSFListener.java: -------------------------------------------------------------------------------- 1 | package com.bing.excel.reader.hssf; 2 | 3 | /* ==================================================================== 4 | Licensed to the Apache Software Foundation (ASF) under one or more 5 | contributor license agreements. See the NOTICE file distributed with 6 | this work for additional information regarding copyright ownership. 7 | The ASF licenses this file to You under the Apache License, Version 2.0 8 | (the "License"); you may not use this file except in compliance with 9 | the License. You may obtain a copy of the License at 10 | 11 | http://www.apache.org/licenses/LICENSE-2.0 12 | 13 | Unless required by applicable law or agreed to in writing, software 14 | distributed under the License is distributed on an "AS IS" BASIS, 15 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | See the License for the specific language governing permissions and 17 | limitations under the License. 18 | ==================================================================== */ 19 | 20 | import java.text.NumberFormat; 21 | import java.util.ArrayList; 22 | import java.util.Hashtable; 23 | import java.util.List; 24 | import java.util.Locale; 25 | import java.util.Map; 26 | 27 | import org.apache.poi.hssf.eventusermodel.HSSFListener; 28 | import org.apache.poi.hssf.record.CellValueRecordInterface; 29 | import org.apache.poi.hssf.record.ExtendedFormatRecord; 30 | import org.apache.poi.hssf.record.FormatRecord; 31 | import org.apache.poi.hssf.record.FormulaRecord; 32 | import org.apache.poi.hssf.record.NumberRecord; 33 | import org.apache.poi.hssf.record.Record; 34 | import org.apache.poi.util.LocaleUtil; 35 | import org.apache.poi.util.POILogFactory; 36 | import org.apache.poi.util.POILogger; 37 | 38 | import com.bing.excel.reader.usermodel.ExcelHSSFDataFormatter; 39 | import com.bing.excel.reader.usermodel.ExcelHSSFDataFormat; 40 | 41 | 42 | /** 43 | * A proxy HSSFListener that keeps track of the document formatting records, and 44 | * provides an easy way to look up the format strings used by cells from their 45 | * ids. 46 | */ 47 | /** 48 | * @author shizhongtao 49 | * 50 | * date 2016-2-17 51 | * Description: 52 | */ 53 | public class ExcelFormatTrackingHSSFListener implements HSSFListener { 54 | private static POILogger logger = POILogFactory.getLogger(ExcelFormatTrackingHSSFListener.class); 55 | private final HSSFListener _childListener; 56 | private final ExcelHSSFDataFormatter _formatter; 57 | private final NumberFormat _defaultFormat; 58 | private final Map _customFormatRecords = new Hashtable(); 59 | private final List _xfRecords = new ArrayList(); 60 | 61 | /** 62 | * Creates a format tracking wrapper around the given listener, using 63 | * the {@link Locale#getDefault() default locale} for the formats. 64 | */ 65 | public ExcelFormatTrackingHSSFListener(HSSFListener childListener) { 66 | this(childListener, LocaleUtil.getUserLocale()); 67 | } 68 | 69 | /** 70 | * Creates a format tracking wrapper around the given listener, using 71 | * the given locale for the formats. 72 | */ 73 | public ExcelFormatTrackingHSSFListener( 74 | HSSFListener childListener, Locale locale) { 75 | _childListener = childListener; 76 | _formatter = new ExcelHSSFDataFormatter(locale); 77 | _defaultFormat = NumberFormat.getInstance(locale); 78 | } 79 | 80 | protected int getNumberOfCustomFormats() { 81 | return _customFormatRecords.size(); 82 | } 83 | 84 | protected int getNumberOfExtendedFormats() { 85 | return _xfRecords.size(); 86 | } 87 | 88 | /** 89 | * Process this record ourselves, and then pass it on to our child listener 90 | */ 91 | public void processRecord(Record record) { 92 | // Handle it ourselves 93 | processRecordInternally(record); 94 | 95 | // Now pass on to our child 96 | _childListener.processRecord(record); 97 | } 98 | 99 | /** 100 | * Process the record ourselves, but do not pass it on to the child 101 | * Listener. 102 | * 103 | * @param record 104 | */ 105 | public void processRecordInternally(Record record) { 106 | if (record instanceof FormatRecord) { 107 | FormatRecord fr = (FormatRecord) record; 108 | _customFormatRecords.put(Integer.valueOf(fr.getIndexCode()), fr); 109 | } 110 | if (record instanceof ExtendedFormatRecord) { 111 | ExtendedFormatRecord xr = (ExtendedFormatRecord) record; 112 | _xfRecords.add(xr); 113 | } 114 | } 115 | 116 | /** 117 | * Formats the given numeric of date Cell's contents as a String, in as 118 | * close as we can to the way that Excel would do so. Uses the various 119 | * format records to manage this. 120 | * 121 | * TODO - move this to a central class in such a way that hssf.usermodel can 122 | * make use of it too 123 | */ 124 | public String formatNumberDateCell(CellValueRecordInterface cell) { 125 | double value; 126 | if (cell instanceof NumberRecord) { 127 | value = ((NumberRecord) cell).getValue(); 128 | } else if (cell instanceof FormulaRecord) { 129 | value = ((FormulaRecord) cell).getValue(); 130 | } else { 131 | throw new IllegalArgumentException("Unsupported CellValue Record passed in " + cell); 132 | } 133 | 134 | // Get the built in format, if there is one 135 | int formatIndex = getFormatIndex(cell); 136 | String formatString = getFormatString(cell); 137 | 138 | if (formatString == null) { 139 | return _defaultFormat.format(value); 140 | } 141 | // Format, using the nice new 142 | // HSSFDataFormatter to do the work for us 143 | return _formatter.formatRawCellContents(value, formatIndex, formatString); 144 | } 145 | 146 | /** 147 | * Returns the format string, eg $##.##, for the given number format index. 148 | */ 149 | public String getFormatString(int formatIndex) { 150 | String format = null; 151 | if (formatIndex >= ExcelHSSFDataFormat.getNumberOfBuiltinBuiltinFormats()) { 152 | FormatRecord tfr = _customFormatRecords.get(Integer.valueOf(formatIndex)); 153 | if (tfr == null) { 154 | logger.log( POILogger.ERROR, "Requested format at index " + formatIndex 155 | + ", but it wasn't found"); 156 | } else { 157 | format = tfr.getFormatString(); 158 | } 159 | } else { 160 | format = ExcelHSSFDataFormat.getBuiltinFormat((short) formatIndex); 161 | } 162 | return format; 163 | } 164 | 165 | /** 166 | * Returns the format string, eg $##.##, used by your cell 167 | */ 168 | public String getFormatString(CellValueRecordInterface cell) { 169 | int formatIndex = getFormatIndex(cell); 170 | if (formatIndex == -1) { 171 | // Not found 172 | return null; 173 | } 174 | return getFormatString(formatIndex); 175 | } 176 | 177 | /** 178 | * Returns the index of the format string, used by your cell, or -1 if none 179 | * found 180 | */ 181 | public int getFormatIndex(CellValueRecordInterface cell) { 182 | ExtendedFormatRecord xfr = _xfRecords.get(cell.getXFIndex()); 183 | if (xfr == null) { 184 | logger.log( POILogger.ERROR, "Cell " + cell.getRow() + "," + cell.getColumn() 185 | + " uses XF with index " + cell.getXFIndex() + ", but we don't have that"); 186 | return -1; 187 | } 188 | 189 | return xfr.getFormatIndex(); 190 | } 191 | public void ignoreNumFormat(boolean b){ 192 | _formatter.setIgnoreNumFormat(b); 193 | } 194 | 195 | 196 | } 197 | -------------------------------------------------------------------------------- /excel/src/main/java/com/bing/utils/ReflectDependencyFactory.java: -------------------------------------------------------------------------------- 1 | package com.bing.utils; 2 | 3 | import java.lang.reflect.Constructor; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.util.ArrayList; 6 | import java.util.Arrays; 7 | import java.util.Comparator; 8 | import java.util.List; 9 | import com.google.common.primitives.Primitives; 10 | 11 | /** 12 | * @author shizhongtao 13 | * 14 | * date 2016-2-29 Description: 15 | * 16 | */ 17 | 18 | public class ReflectDependencyFactory { 19 | /** 20 | * 根据参数数组,构造实例 21 | * @param type object类型 22 | * @param args 参数 23 | * @return 24 | */ 25 | 26 | public static Object newInstance(final Class type, 27 | final Object[] args) { 28 | if (args != null && args.length > 50) { 29 | throw new IllegalArgumentException( 30 | "More than 50 arguments are not supported"); 31 | } 32 | Constructor bestMatchingCtor = null; 33 | final ArrayList matchingDependencies = new ArrayList(); 34 | List possibleMatchingDependencies = null; 35 | long usedDeps = 0; 36 | long possibleUsedDeps = 0; 37 | 38 | if (args != null && args.length > 0) { 39 | // sort available ctors according their arity, desc 40 | final Constructor[] ctors = type.getConstructors(); 41 | if (ctors.length > 1) { 42 | Arrays.sort(ctors, new Comparator() { 43 | public int compare(final Object o1, final Object o2) { 44 | return ((Constructor) o2).getParameterTypes().length 45 | - ((Constructor) o1).getParameterTypes().length; 46 | } 47 | }); 48 | } 49 | 50 | final TypedValue[] typedDependencies = new TypedValue[args.length]; 51 | for (int i = 0; i < args.length; i++) { 52 | Object dependency = args[i]; 53 | Class depType = dependency.getClass(); 54 | if (depType.isPrimitive()) { 55 | depType = Primitives.wrap(depType); 56 | } 57 | //传入之前,没有考虑null值的转换。 58 | 59 | typedDependencies[i] = new TypedValue(depType, dependency); 60 | } 61 | 62 | Constructor possibleCtor = null; 63 | int arity = Integer.MAX_VALUE; 64 | for (int i = 0; bestMatchingCtor == null && i < ctors.length; i++) { 65 | final Constructor constructor = ctors[i]; 66 | final Class[] parameterTypes = constructor.getParameterTypes(); 67 | if (parameterTypes.length > args.length) { 68 | continue; 69 | } else if (parameterTypes.length == 0) { 70 | if (possibleCtor == null) { 71 | bestMatchingCtor = constructor; 72 | } 73 | break; 74 | } 75 | if (arity > parameterTypes.length) { 76 | if (possibleCtor != null) { 77 | continue; 78 | } 79 | arity = parameterTypes.length; 80 | } 81 | 82 | for (int j = 0; j < parameterTypes.length; j++) { 83 | if (parameterTypes[j].isPrimitive()) { 84 | parameterTypes[j] = Primitives.wrap(parameterTypes[j]); 85 | } 86 | } 87 | 88 | // first approach: aoptest the ctor params against the dependencies 89 | // in the sequence 90 | // of the parameter declaration 91 | matchingDependencies.clear(); 92 | usedDeps = 0; 93 | 94 | for (int j = 0, k = 0; j < parameterTypes.length 95 | && parameterTypes.length + k - j <= typedDependencies.length; k++) { 96 | //确保有一个参数能对上 97 | if (parameterTypes[j].isAssignableFrom(typedDependencies[k].type)) { 98 | matchingDependencies.add(typedDependencies[k].value); 99 | usedDeps |= 1L << k; 100 | if (++j == parameterTypes.length) { 101 | bestMatchingCtor = constructor; 102 | break; 103 | } 104 | } 105 | } 106 | 107 | if (bestMatchingCtor == null) { 108 | boolean possible = true; // assumption 109 | 110 | // try to match all dependencies in the sequence of the 111 | // parameter 112 | // declaration 113 | final TypedValue[] deps = new TypedValue[typedDependencies.length]; 114 | System.arraycopy(typedDependencies, 0, deps, 0, deps.length); 115 | matchingDependencies.clear(); 116 | usedDeps = 0; 117 | for (int j = 0; j < parameterTypes.length; j++) { 118 | int assignable = -1; 119 | for (int k = 0; k < deps.length; k++) { 120 | if (deps[k] == null) { 121 | continue; 122 | } 123 | if (deps[k].type == parameterTypes[j]) { 124 | assignable = k; 125 | // optimal match 126 | break; 127 | } else if (parameterTypes[j] 128 | .isAssignableFrom(deps[k].type)) { 129 | // use most specific type 130 | if (assignable < 0 131 | || (deps[assignable].type != deps[k].type && deps[assignable].type 132 | .isAssignableFrom(deps[k].type))) { 133 | assignable = k; 134 | } 135 | } 136 | } 137 | 138 | if (assignable >= 0) { 139 | matchingDependencies.add(deps[assignable].value); 140 | usedDeps |= 1L << assignable; 141 | deps[assignable] = null; // do not match same dep 142 | // twice 143 | } else { 144 | possible = false; 145 | break; 146 | } 147 | } 148 | 149 | if (possible) { 150 | // the smaller the value, the smaller the indices in the 151 | // deps array 152 | if (possibleCtor != null 153 | && usedDeps >= possibleUsedDeps) { 154 | continue; 155 | } 156 | possibleCtor = constructor; 157 | possibleMatchingDependencies = (List) matchingDependencies 158 | .clone(); 159 | possibleUsedDeps = usedDeps; 160 | } 161 | } 162 | } 163 | 164 | if (bestMatchingCtor == null) { 165 | if (possibleCtor == null) { 166 | usedDeps = 0; 167 | throw new IllegalArgumentException( 168 | "Cannot construct " 169 | + type.getName() 170 | + ", none of the dependencies match any constructor's parameters"); 171 | } else { 172 | bestMatchingCtor = possibleCtor; 173 | matchingDependencies.clear(); 174 | matchingDependencies.addAll(possibleMatchingDependencies); 175 | usedDeps = possibleUsedDeps; 176 | } 177 | } 178 | } 179 | 180 | try { 181 | final Object instance; 182 | if (bestMatchingCtor == null) { 183 | instance = type.newInstance(); 184 | } else { 185 | instance = bestMatchingCtor.newInstance(matchingDependencies 186 | .toArray()); 187 | } 188 | 189 | return instance; 190 | } catch (final InstantiationException e) { 191 | throw new IllegalArgumentException("Cannot construct " 192 | + type.getName(), e); 193 | } catch (final IllegalAccessException e) { 194 | throw new IllegalArgumentException("Cannot construct " 195 | + type.getName(), e); 196 | } catch (final InvocationTargetException e) { 197 | throw new IllegalArgumentException("Cannot construct " 198 | + type.getName(), e); 199 | } catch (final SecurityException e) { 200 | throw new IllegalArgumentException("Cannot construct " 201 | + type.getName(), e); 202 | } catch (final ExceptionInInitializerError e) { 203 | throw new IllegalArgumentException("Cannot construct " 204 | + type.getName(), e); 205 | } 206 | } 207 | 208 | private static class TypedValue { 209 | final Class type; 210 | final Object value; 211 | 212 | public TypedValue(final Class type, final Object value) { 213 | super(); 214 | this.type = type; 215 | this.value = value; 216 | } 217 | 218 | public String toString() { 219 | return type.getName() + ":" + value; 220 | } 221 | } 222 | } 223 | --------------------------------------------------------------------------------