diff --git a/pom.xml b/pom.xml index 26c45a59..bae1f5f6 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ 4.0.0 com.alibaba easyexcel - 1.1.1 + 1.1.2-beat1 jar easyexcel @@ -67,9 +67,9 @@ 3.17 - commons-beanutils - commons-beanutils - 1.9.2 + cglib + cglib + 3.1 junit @@ -77,11 +77,7 @@ 4.12 test - - org.apache.commons - commons-compress - 1.14 - + diff --git a/src/main/java/com/alibaba/excel/EasyExcelFactory.java b/src/main/java/com/alibaba/excel/EasyExcelFactory.java new file mode 100644 index 00000000..fae2fe61 --- /dev/null +++ b/src/main/java/com/alibaba/excel/EasyExcelFactory.java @@ -0,0 +1,100 @@ +package com.alibaba.excel; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; +import com.alibaba.excel.metadata.Sheet; +import com.alibaba.excel.support.ExcelTypeEnum; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.List; + +/** + * Reader and writer factory class + * + * @author jipengfei + */ +public class EasyExcelFactory { + + /** + * Quickly read small files,no more than 10,000 lines. + * + * @param in the POI filesystem that contains the Workbook stream. + * @param sheet read sheet. + * @return analysis result. + */ + public static List read(InputStream in, Sheet sheet) { + final List rows = new ArrayList(); + new ExcelReader(in, null, new AnalysisEventListener() { + @Override + public void invoke(Object object, AnalysisContext context) { + rows.add(object); + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + } + }, false).read(sheet); + return rows; + } + + /** + * Parsing large file + * + * @param in the POI filesystem that contains the Workbook stream. + * @param sheet read sheet. + * @param listener Callback method after each row is parsed. + */ + public static void readBySax(InputStream in, Sheet sheet, AnalysisEventListener listener) { + new ExcelReader(in, null, listener).read(sheet); + } + + /** + * Get ExcelReader. + * + * @param in the POI filesystem that contains the Workbook stream. + * @param listener Callback method after each row is parsed. + * @return ExcelReader. + */ + public static ExcelReader getReader(InputStream in, AnalysisEventListener listener) { + return new ExcelReader(in, null, listener); + } + + /** + * Get ExcelWriter + * + * @param outputStream the java OutputStream you wish to write the data to. + * @return new ExcelWriter. + */ + public static ExcelWriter getWriter(OutputStream outputStream) { + return new ExcelWriter(outputStream, ExcelTypeEnum.XLSX, true); + } + + /** + * Get ExcelWriter + * + * @param outputStream the java OutputStream you wish to write the data to. + * @param typeEnum 03 or 07 + * @param needHead Do you need to write the header to the file? + * @return new ExcelWriter + */ + public static ExcelWriter getWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { + return new ExcelWriter(outputStream, typeEnum, needHead); + } + + /** + * Get ExcelWriter with a template file + * + * @param temp Append data after a POI file , Can be null(the template POI filesystem that contains the + * Workbook stream) + * @param outputStream the java OutputStream you wish to write the data to + * @param typeEnum 03 or 07 + * @return new ExcelWriter + */ + public static ExcelWriter getWriterWithTemp(InputStream temp, OutputStream outputStream, ExcelTypeEnum typeEnum, + boolean needHead) { + return new ExcelWriter(temp, outputStream, typeEnum, needHead); + } + +} diff --git a/src/main/java/com/alibaba/excel/ExcelReader.java b/src/main/java/com/alibaba/excel/ExcelReader.java index bba06b0b..9ed58927 100644 --- a/src/main/java/com/alibaba/excel/ExcelReader.java +++ b/src/main/java/com/alibaba/excel/ExcelReader.java @@ -13,23 +13,24 @@ import java.io.InputStream; import java.util.List; /** - * Excel thread unsafe + * Excel readers are all read in event mode. * * @author jipengfei */ public class ExcelReader { /** - * analyser + * Analyser */ - private ExcelAnalyser analyser = new ExcelAnalyserImpl(); + private ExcelAnalyser analyser ; /** - * @param in - * @param excelTypeEnum 0307 - * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) - * }AnalysisContext - * @param eventListener + * Create new reader + * + * @param in the POI filesystem that contains the Workbook stream + * @param excelTypeEnum 03 or 07 + * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext + * @param eventListener Callback method after each row is parsed. */ @Deprecated public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, @@ -38,10 +39,11 @@ public class ExcelReader { } /** - * @param in - * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) - * }AnalysisContext - * @param eventListener + * Create new reader + * + * @param in the POI filesystem that contains the Workbook stream + * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext + * @param eventListener Callback method after each row is parsed */ public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener) { @@ -49,8 +51,10 @@ public class ExcelReader { } /** - * @param param - * @param eventListener + * Create new reader + * + * @param param old param Deprecated + * @param eventListener Callback method after each row is parsed. */ @Deprecated public ExcelReader(AnalysisParam param, AnalysisEventListener eventListener) { @@ -58,75 +62,88 @@ public class ExcelReader { } /** - * @param in - * @param excelTypeEnum 03 07 - * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) - * }AnalysisContext - * @param eventListener - * @param trim + * Create new reader + * + * @param in the POI filesystem that contains the Workbook stream + * @param excelTypeEnum 03 or 07 + * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext + * @param eventListener Callback method after each row is parsed. + * @param trim The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, + * because there are often table contents with spaces that can not be converted into custom + * types. For example: '1234 ' contain a space cannot be converted to int. */ @Deprecated public ExcelReader(InputStream in, ExcelTypeEnum excelTypeEnum, Object customContent, AnalysisEventListener eventListener, boolean trim) { - validateParam(in, excelTypeEnum, eventListener); - analyser.init(in, excelTypeEnum, customContent, eventListener, trim); + validateParam(in, eventListener); + analyser = new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim); } /** + * Create new reader + * * @param in - * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) - * }AnalysisContext + * @param customContent {@link AnalysisEventListener#invoke(Object, AnalysisContext) }AnalysisContext * @param eventListener - * @param trim + * @param trim The content of the form is empty and needs to be empty. The purpose is to be fault-tolerant, + * because there are often table contents with spaces that can not be converted into custom + * types. For example: '1234 ' contain a space cannot be converted to int. */ public ExcelReader(InputStream in, Object customContent, AnalysisEventListener eventListener, boolean trim) { ExcelTypeEnum excelTypeEnum = ExcelTypeEnum.valueOf(in); - validateParam(in, excelTypeEnum, eventListener); - analyser.init(in, excelTypeEnum, customContent, eventListener, trim); + validateParam(in, eventListener); + analyser =new ExcelAnalyserImpl(in, excelTypeEnum, customContent, eventListener, trim); } /** + * Parse all sheet content by default */ public void read() { analyser.analysis(); } /** + * Parse the specified sheet,SheetNo start from 1 * - * @param sheet + * @param sheet Read sheet */ public void read(Sheet sheet) { analyser.analysis(sheet); } + /** + * Parse the specified sheet + * + * @param sheet Read sheet + * @param clazz object parsed into each row of data + */ @Deprecated - public void read(Sheet sheet,Class clazz){ + public void read(Sheet sheet, Class clazz) { sheet.setClazz(clazz); analyser.analysis(sheet); } /** + * Parse the workBook get all sheets * - * @return + * @return workBook all sheets */ public List getSheets() { return analyser.getSheets(); } /** + * validate param * * @param in - * @param excelTypeEnum * @param eventListener */ - private void validateParam(InputStream in, ExcelTypeEnum excelTypeEnum, AnalysisEventListener eventListener) { + private void validateParam(InputStream in, AnalysisEventListener eventListener) { if (eventListener == null) { throw new IllegalArgumentException("AnalysisEventListener can not null"); } else if (in == null) { throw new IllegalArgumentException("InputStream can not null"); - } else if (excelTypeEnum == null) { - throw new IllegalArgumentException("excelTypeEnum can not null"); } } } diff --git a/src/main/java/com/alibaba/excel/ExcelWriter.java b/src/main/java/com/alibaba/excel/ExcelWriter.java index c526e999..a8dda851 100644 --- a/src/main/java/com/alibaba/excel/ExcelWriter.java +++ b/src/main/java/com/alibaba/excel/ExcelWriter.java @@ -13,7 +13,12 @@ import java.io.OutputStream; import java.util.List; /** - * + * Excel Writer This tool is used to write data out to Excel via POI. + * This object can perform the following two functions. + *
+ *    1. Create a new empty Excel workbook, write the data to the stream after the data is filled.
+ *    2. Edit existing Excel, write the original Excel file, or write it to other places.{@link ExcelWriter(InputStream , OutputStream , ExcelTypeEnum , boolean )}
+ * 
* @author jipengfei */ public class ExcelWriter { @@ -21,66 +26,65 @@ public class ExcelWriter { private ExcelBuilder excelBuilder; /** - * - * + * Create new writer + * @param outputStream the java OutputStream you wish to write the data to + * @param typeEnum 03 or 07 */ public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum) { this(outputStream, typeEnum, true); } + @Deprecated private Class objectClass; - private String sheetName; - + /** + * @param generateParam + * @since easyexcel 0.0.1 Use {@link new ExcelWrite(int, int, int) + */ + @Deprecated public ExcelWriter(GenerateParam generateParam) { - this(generateParam.getOutputStream(), generateParam.getType(), true); this.objectClass = generateParam.getClazz(); - this.sheetName = generateParam.getSheetName(); } /** * - * - * @param outputStream - * @param typeEnum + * Create new writer + * @param outputStream the java OutputStream you wish to write the data to + * @param typeEnum 03 or 07 + * @param needHead Do you need to write the header to the file? */ public ExcelWriter(OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - excelBuilder = new ExcelBuilderImpl(); - excelBuilder.init(null, outputStream, typeEnum, needHead); + excelBuilder = new ExcelBuilderImpl(null, outputStream, typeEnum, needHead); } /** - * - * @param templateInputStream - * @param outputStream - * @param typeEnum + * Create new writer + * @param templateInputStream Append data after a POI file ,Can be null(the template POI filesystem that contains the Workbook stream) + * @param outputStream the java OutputStream you wish to write the data to + * @param typeEnum 03 or 07 */ - public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum, boolean needHead) { - excelBuilder = new ExcelBuilderImpl(); - excelBuilder.init(templateInputStream,outputStream, typeEnum, needHead); + public ExcelWriter(InputStream templateInputStream, OutputStream outputStream, ExcelTypeEnum typeEnum,Boolean needHead) { + excelBuilder = new ExcelBuilderImpl(templateInputStream,outputStream, typeEnum, needHead); } /** - * - * @param data - * @param sheet - * @return this + * Write data(List) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet + * @return this current writer */ public ExcelWriter write(List data, Sheet sheet) { excelBuilder.addContent(data, sheet); return this; } - //public Sheet(int sheetNo, int headLineMun, Class clazz, String sheetName, - // List> head) { - // this.sheetNo = sheetNo; - // this.clazz = clazz; - // this.headLineMun = headLineMun; - // this.sheetName = sheetName; - // this.head = head; - //} + /** + * Write data to a sheet + * @param data Data to be written + * @return this current writer + */ @Deprecated public ExcelWriter write(List data) { if (objectClass != null) { @@ -93,9 +97,9 @@ public class ExcelWriter { /** * - * - * @param data - * @param sheet + * Write data(List>) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet * @return this */ public ExcelWriter write1(List> data, Sheet sheet) { @@ -104,9 +108,9 @@ public class ExcelWriter { } /** - * - * @param data - * @param sheet + * Write data(List>) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet * @return this */ public ExcelWriter write0(List> data, Sheet sheet) { @@ -114,25 +118,58 @@ public class ExcelWriter { return this; } - - + /** + * Write data(List) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet + * @param table Write to this table + * @return this + */ public ExcelWriter write(List data, Sheet sheet, Table table) { excelBuilder.addContent(data, sheet, table); return this; } - + /** + * Write data(List>) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet + * @param table Write to this table + * @return this + */ public ExcelWriter write0(List> data, Sheet sheet, Table table) { excelBuilder.addContent(data, sheet, table); return this; } + /** + * Merge Cells,Indexes are zero-based. + * + * @param firstRow Index of first row + * @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow} + * @param firstCol Index of first column + * @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol} + */ + public ExcelWriter merge(int firstRow, int lastRow, int firstCol, int lastCol){ + excelBuilder.merge(firstRow,lastRow,firstCol,lastCol); + return this; + } + /** + * Write data(List>) to a sheet + * @param data Data to be written + * @param sheet Write to this sheet + * @param table Write to this table + * @return + */ public ExcelWriter write1(List> data, Sheet sheet, Table table) { excelBuilder.addContent(data, sheet, table); return this; } + /** + * Close IO + */ public void finish() { excelBuilder.finish(); } diff --git a/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java index 55e906c9..54f7b557 100644 --- a/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/BaseSaxAnalyser.java @@ -5,17 +5,14 @@ import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.event.AnalysisEventRegisterCenter; import com.alibaba.excel.event.OneRowAnalysisFinishEvent; import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.util.TypeUtil; -import java.io.InputStream; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** - * * @author jipengfei */ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, ExcelAnalyser { @@ -25,46 +22,51 @@ public abstract class BaseSaxAnalyser implements AnalysisEventRegisterCenter, Ex private LinkedHashMap listeners = new LinkedHashMap(); /** + * execute method */ protected abstract void execute(); - public void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, - AnalysisEventListener eventListener, boolean trim) { - } + @Override public void appendLister(String name, AnalysisEventListener listener) { if (!listeners.containsKey(name)) { listeners.put(name, listener); } } + @Override public void analysis(Sheet sheetParam) { execute(); } + @Override public void analysis() { execute(); } /** */ + @Override public void cleanAllListeners() { listeners = new LinkedHashMap(); } + @Override public void notifyListeners(OneRowAnalysisFinishEvent event) { analysisContext.setCurrentRowAnalysisResult(event.getData()); - + /** Parsing header content **/ if (analysisContext.getCurrentRowNum() < analysisContext.getCurrentSheet().getHeadLineMun()) { if (analysisContext.getCurrentRowNum() <= analysisContext.getCurrentSheet().getHeadLineMun() - 1) { analysisContext.buildExcelHeadProperty(null, (List)analysisContext.getCurrentRowAnalysisResult()); } } else { + /** Parsing Analyze the body content **/ analysisContext.setCurrentRowAnalysisResult(event.getData()); if (listeners.size() == 1) { analysisContext.setCurrentRowAnalysisResult(converter((List)event.getData())); } + /** notify all event listeners **/ for (Map.Entry entry : listeners.entrySet()) { entry.getValue().invoke(analysisContext.getCurrentRowAnalysisResult(), analysisContext); } diff --git a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java index aef773d3..b5aef4d0 100644 --- a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyser.java @@ -1,30 +1,33 @@ package com.alibaba.excel.analysis; -import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import java.io.InputStream; import java.util.List; /** + * Excel file analyser * * @author jipengfei */ public interface ExcelAnalyser { - void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, AnalysisEventListener eventListener, - boolean trim); - + /** + * parse one sheet + * + * @param sheetParam + */ void analysis(Sheet sheetParam); - - + /** + * parse all sheets + */ void analysis(); - + /** + * get all sheet of workbook + * + * @return all sheets + */ List getSheets(); - - } diff --git a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java index 3283698e..33e60530 100644 --- a/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java +++ b/src/main/java/com/alibaba/excel/analysis/ExcelAnalyserImpl.java @@ -22,41 +22,61 @@ public class ExcelAnalyserImpl implements ExcelAnalyser { private BaseSaxAnalyser saxAnalyser; + public ExcelAnalyserImpl(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, + AnalysisEventListener eventListener, boolean trim) { + analysisContext = new AnalysisContextImpl(inputStream, excelTypeEnum, custom, + eventListener, trim); + } + + private BaseSaxAnalyser getSaxAnalyser() { - if (saxAnalyser == null) { - try { - if (ExcelTypeEnum.XLS.equals(analysisContext.getExcelType())) { - this.saxAnalyser = new XlsSaxAnalyser(analysisContext); - } else { + if (saxAnalyser != null) { + return this.saxAnalyser; + } + try { + if (analysisContext.getExcelType() != null) { + switch (analysisContext.getExcelType()) { + case XLS: + this.saxAnalyser = new XlsSaxAnalyser(analysisContext); + break; + case XLSX: + this.saxAnalyser = new XlsxSaxAnalyser(analysisContext); + break; + } + } else { + try { this.saxAnalyser = new XlsxSaxAnalyser(analysisContext); + } catch (Exception e) { + if (!analysisContext.getInputStream().markSupported()) { + throw new ExcelAnalysisException( + "Xls must be available markSupported,you can do like this new " + + "BufferedInputStream(new FileInputStream(\"/xxxx/xxx/77.xlsx\")) "); + } + this.saxAnalyser = new XlsSaxAnalyser(analysisContext); } - } catch (Exception e) { - throw new ExcelAnalysisException("Analyse excel occur file error fileType " + analysisContext.getExcelType(), - e); } + } catch (Exception e) { + throw new ExcelAnalysisException("File type error,io must be available markSupported,you can do like " + + "this new BufferedInputStream(new FileInputStream(\\\"/xxxx/xxx/77.xlsx\\\")) \"", e); } return this.saxAnalyser; } - public void init(InputStream inputStream, ExcelTypeEnum excelTypeEnum, Object custom, - AnalysisEventListener eventListener, boolean trim) { - analysisContext = new AnalysisContextImpl(inputStream, excelTypeEnum, custom, - eventListener, trim); - } - + @Override public void analysis(Sheet sheetParam) { analysisContext.setCurrentSheet(sheetParam); analysis(); } + @Override public void analysis() { BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); appendListeners(saxAnalyser); saxAnalyser.execute(); - analysisContext.getEventListener().doAfterAllAnalysed(analysisContext); } + @Override public List getSheets() { BaseSaxAnalyser saxAnalyser = getSaxAnalyser(); saxAnalyser.cleanAllListeners(); @@ -64,6 +84,7 @@ public class ExcelAnalyserImpl implements ExcelAnalyser { } private void appendListeners(BaseSaxAnalyser saxAnalyser) { + saxAnalyser.cleanAllListeners(); if (analysisContext.getCurrentSheet() != null && analysisContext.getCurrentSheet().getClazz() != null) { saxAnalyser.appendLister("model_build_listener", new ModelBuildEventListener()); } diff --git a/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java index bfaa3e9f..01546254 100644 --- a/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v03/XlsSaxAnalyser.java @@ -18,6 +18,10 @@ import java.util.ArrayList; import java.util.List; /** + * /** * A text extractor for Excel files. *

* Returns the textual content of the file, suitable for * indexing by + * something like Lucene, but not really * intended for display to the user. *

*

* To turn an excel file into + * a CSV or similar, then see * the XLS2CSVmra example *

* * @see + * XLS2CSVmra * * @author jipengfei */ @@ -36,6 +40,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { } + @Override public List getSheets() { execute(); return sheets; @@ -104,27 +109,19 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { */ private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener; private HSSFWorkbook stubWorkbook; - - // Records we pick up as we process private SSTRecord sstRecord; private FormatTrackingHSSFListener formatListener; /** * So we known which sheet we're on */ - // private BoundSheetRecord[] orderedBSRs; - - // @SuppressWarnings("rawtypes") - // private ArrayList boundSheetRecords = new ArrayList(); - // For handling formulas with string results private int nextRow; private int nextColumn; private boolean outputNextStringRecord; /** - * Main HSSFListener method, processes events, and outputs the CSV as the - * file is processed. + * Main HSSFListener method, processes events, and outputs the CSV as the file is processed. */ private int sheetIndex; @@ -281,10 +278,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { // If we got something to print out, do so if (thisStr != null) { - //if (thisColumn > 1) { - // // output.print(','); - //} - //if (thisStr != null) { + if (analysisContext.trim()) { thisStr = thisStr.trim(); } @@ -292,7 +286,6 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { notAllEmpty = true; } // } - // output.print(thisStr); records.add(thisStr); } @@ -307,9 +300,7 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { // Handle end of row if (record instanceof LastCellOfRowDummyRecord) { thisRow = ((LastCellOfRowDummyRecord)record).getRow(); - // thisColumn = ((LastCellOfRowDummyRecord) - // record).getLastColumnNumber(); - // Columns are 0 based + if (lastColumnNumber == -1) { lastColumnNumber = 0; } @@ -317,26 +308,11 @@ public class XlsSaxAnalyser extends BaseSaxAnalyser implements HSSFListener { Sheet sheet = analysisContext.getCurrentSheet(); if ((sheet == null || sheet.getSheetNo() == sheetIndex) && notAllEmpty) { - notifyListeners(new OneRowAnalysisFinishEvent(copyList(records))); + notifyListeners(new OneRowAnalysisFinishEvent(records)); } - // System.out.println(records); records.clear(); lastColumnNumber = -1; notAllEmpty = false; - } } - - private List copyList(List data) { - if (data == null) { - return null; - } - List list = new ArrayList(); - for (String str : data) { - list.add(new String(str)); - } - return list; - - } - } diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java index 4788ff21..abc309d2 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxRowHandler.java @@ -17,7 +17,9 @@ import java.util.Arrays; import static com.alibaba.excel.constant.ExcelXmlConstants.*; /** + * * @author jipengfei + * @date 2017/08/23 */ public class XlsxRowHandler extends DefaultHandler { @@ -81,11 +83,6 @@ public class XlsxRowHandler extends DefaultHandler { if (cellType != null && cellType.equals("s")) { currentCellType = FieldType.STRING; } - //if ("6".equals(attributes.getValue("s"))) { - // // date - // currentCellType = FieldType.DATE; - //} - } } @@ -102,12 +99,6 @@ public class XlsxRowHandler extends DefaultHandler { currentCellValue = new XSSFRichTextString(sst.getEntryAt(idx)).toString(); currentCellType = FieldType.EMPTY; break; - //case DATE: - // Date dateVal = HSSFDateUtil.getJavaDate(Double.parseDouble(currentCellValue), - // analysisContext.use1904WindowDate()); - // currentCellValue = TypeUtil.getDefaultDateString(dateVal); - // currentCellType = FieldType.EMPTY; - // break; } curRowContent[curCol] = currentCellValue; } else if (CELL_VALUE_TAG_1.equals(name)) { @@ -117,16 +108,13 @@ public class XlsxRowHandler extends DefaultHandler { @Override public void endElement(String uri, String localName, String name) throws SAXException { - endRow(name); endCellValue(name); } @Override public void characters(char[] ch, int start, int length) throws SAXException { - currentCellValue += new String(ch, start, length); - } @@ -142,7 +130,7 @@ public class XlsxRowHandler extends DefaultHandler { private void endRow(String name) { if (name.equals(ROW_TAG)) { - registerCenter.notifyListeners(new OneRowAnalysisFinishEvent(Arrays.asList(curRowContent))); + registerCenter.notifyListeners(new OneRowAnalysisFinishEvent(curRowContent,curCol)); curRowContent = new String[20]; } } diff --git a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java index a3debed7..0579a0a0 100644 --- a/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java +++ b/src/main/java/com/alibaba/excel/analysis/v07/XlsxSaxAnalyser.java @@ -24,7 +24,9 @@ import java.util.ArrayList; import java.util.List; /** + * * @author jipengfei + * @date 2017/08/27 */ public class XlsxSaxAnalyser extends BaseSaxAnalyser { @@ -34,7 +36,6 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser { private List sheetSourceList = new ArrayList(); - private boolean use1904WindowDate = false; public XlsxSaxAnalyser(AnalysisContext analysisContext) throws IOException, OpenXML4JException, XmlException { @@ -66,6 +67,7 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser { } + @Override protected void execute() { Sheet sheetParam = analysisContext.getCurrentSheet(); if (sheetParam != null && sheetParam.getSheetNo() > 0 && sheetSourceList.size() >= sheetParam.getSheetNo()) { @@ -91,16 +93,17 @@ public class XlsxSaxAnalyser extends BaseSaxAnalyser { saxFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); SAXParser saxParser = saxFactory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); - ContentHandler handler = new XlsxRowHandler(this, sharedStringsTable, analysisContext); xmlReader.setContentHandler(handler); xmlReader.parse(sheetSource); inputStream.close(); } catch (Exception e) { + e.printStackTrace(); throw new ExcelAnalysisException(e); } } + @Override public List getSheets() { List sheets = new ArrayList(); int i = 1; diff --git a/src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java b/src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java index 0958372a..d682830e 100644 --- a/src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java +++ b/src/main/java/com/alibaba/excel/annotation/ExcelColumnNum.java @@ -1,12 +1,17 @@ package com.alibaba.excel.annotation; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * Created by jipengfei on 17/3/19. * Field column num at excel head * * @author jipengfei + * @date 2017/03/19 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java index cc3afc84..a063a327 100644 --- a/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java +++ b/src/main/java/com/alibaba/excel/annotation/ExcelProperty.java @@ -1,6 +1,10 @@ package com.alibaba.excel.annotation; -import java.lang.annotation.*; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; /** * @author jipengfei diff --git a/src/main/java/com/alibaba/excel/annotation/FieldType.java b/src/main/java/com/alibaba/excel/annotation/FieldType.java index 73729959..e5dc48df 100644 --- a/src/main/java/com/alibaba/excel/annotation/FieldType.java +++ b/src/main/java/com/alibaba/excel/annotation/FieldType.java @@ -3,6 +3,7 @@ package com.alibaba.excel.annotation; /** * * @author jipengfei + * @date 2017/03/15 */ public enum FieldType { diff --git a/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java b/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java index dcd2d5a4..8403f9e3 100644 --- a/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java +++ b/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java @@ -2,6 +2,7 @@ package com.alibaba.excel.constant; /** * @author jipengfei + * @date 2017/08/24 */ public class ExcelXmlConstants { public static final String DIMENSION = "dimension"; diff --git a/src/main/java/com/alibaba/excel/context/AnalysisContext.java b/src/main/java/com/alibaba/excel/context/AnalysisContext.java index 2f6b8ac3..23c846f9 100644 --- a/src/main/java/com/alibaba/excel/context/AnalysisContext.java +++ b/src/main/java/com/alibaba/excel/context/AnalysisContext.java @@ -11,71 +11,77 @@ import java.util.List; /** * + * A context is the main anchorage point of a excel reader. * @author jipengfei */ public interface AnalysisContext { /** - * + * Custom attribute */ Object getCustom(); /** + * get current sheet * * @return current analysis sheet */ Sheet getCurrentSheet(); /** - * + * set current sheet * @param sheet */ void setCurrentSheet(Sheet sheet); /** * + * get excel type * @return excel type */ ExcelTypeEnum getExcelType(); /** - * + * get in io * @return file io */ InputStream getInputStream(); /** * - * @return + * custom listener + * @return listener */ AnalysisEventListener getEventListener(); /** - * + * get current row * @return */ Integer getCurrentRowNum(); /** - * + * set current row num * @param row */ void setCurrentRowNum(Integer row); /** - * + * get total row ,Data may be inaccurate * @return */ + @Deprecated Integer getTotalCount(); /** + * get total row ,Data may be inaccurate * * @param totalCount */ void setTotalCount(Integer totalCount); /** - * + * get excel head * @return */ ExcelHeadProperty getExcelHeadProperty(); @@ -89,34 +95,37 @@ public interface AnalysisContext { /** * + *if need to short match the content * @return */ boolean trim(); /** - * + * set current result + * @param result */ void setCurrentRowAnalysisResult(Object result); /** - * + * get current result + * @return get current result */ Object getCurrentRowAnalysisResult(); /** - * + * Interrupt execution */ void interrupt(); /** - * + * date use1904WindowDate * @return */ boolean use1904WindowDate(); /** - * + * date use1904WindowDate * @param use1904WindowDate */ void setUse1904WindowDate(boolean use1904WindowDate); diff --git a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java index 43dae671..fff50552 100644 --- a/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java +++ b/src/main/java/com/alibaba/excel/context/AnalysisContextImpl.java @@ -37,22 +37,27 @@ public class AnalysisContextImpl implements AnalysisContext { private boolean use1904WindowDate = false; + @Override public void setUse1904WindowDate(boolean use1904WindowDate) { this.use1904WindowDate = use1904WindowDate; } + @Override public Object getCurrentRowAnalysisResult() { return currentRowAnalysisResult; } + @Override public void interrupt() { throw new ExcelAnalysisException("interrupt error"); } + @Override public boolean use1904WindowDate() { return use1904WindowDate; } + @Override public void setCurrentRowAnalysisResult(Object currentRowAnalysisResult) { this.currentRowAnalysisResult = currentRowAnalysisResult; } @@ -68,13 +73,24 @@ public class AnalysisContextImpl implements AnalysisContext { this.trim = trim; } + @Override public void setCurrentSheet(Sheet currentSheet) { + cleanCurrentSheet(); this.currentSheet = currentSheet; if (currentSheet.getClazz() != null) { buildExcelHeadProperty(currentSheet.getClazz(), null); } } + private void cleanCurrentSheet() { + this.currentSheet = null; + this.excelHeadProperty = null; + this.totalCount = 0; + this.currentRowAnalysisResult = null; + this.currentRowNum =0; + } + + @Override public ExcelTypeEnum getExcelType() { return excelType; } @@ -91,10 +107,12 @@ public class AnalysisContextImpl implements AnalysisContext { this.custom = custom; } + @Override public Sheet getCurrentSheet() { return currentSheet; } + @Override public InputStream getInputStream() { return inputStream; } @@ -103,6 +121,7 @@ public class AnalysisContextImpl implements AnalysisContext { this.inputStream = inputStream; } + @Override public AnalysisEventListener getEventListener() { return eventListener; } @@ -111,26 +130,32 @@ public class AnalysisContextImpl implements AnalysisContext { this.eventListener = eventListener; } + @Override public Integer getCurrentRowNum() { return this.currentRowNum; } + @Override public void setCurrentRowNum(Integer row) { this.currentRowNum = row; } + @Override public Integer getTotalCount() { return totalCount; } + @Override public void setTotalCount(Integer totalCount) { this.totalCount = totalCount; } + @Override public ExcelHeadProperty getExcelHeadProperty() { return this.excelHeadProperty; } + @Override public void buildExcelHeadProperty(Class clazz, List headOneRow) { if (this.excelHeadProperty == null && (clazz != null || headOneRow != null)) { this.excelHeadProperty = new ExcelHeadProperty(clazz, new ArrayList>()); @@ -140,6 +165,7 @@ public class AnalysisContextImpl implements AnalysisContext { } } + @Override public boolean trim() { return this.trim; } diff --git a/src/main/java/com/alibaba/excel/context/GenerateContext.java b/src/main/java/com/alibaba/excel/context/GenerateContext.java deleted file mode 100644 index 5d74b2d6..00000000 --- a/src/main/java/com/alibaba/excel/context/GenerateContext.java +++ /dev/null @@ -1,66 +0,0 @@ -package com.alibaba.excel.context; - -import com.alibaba.excel.metadata.ExcelHeadProperty; -import com.alibaba.excel.metadata.Table; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.Workbook; - -import java.io.OutputStream; - -/** - * @author jipengfei - */ -public interface GenerateContext { - - - /** - * @return current analysis sheet - */ - Sheet getCurrentSheet(); - - /** - * - * @return - */ - CellStyle getCurrentHeadCellStyle(); - - /** - * @return - */ - CellStyle getCurrentContentStyle(); - - - /** - * @return - */ - Workbook getWorkbook(); - - /** - * @return - */ - OutputStream getOutputStream(); - - /** - * @param sheet - */ - void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet); - - /** - * @param table - */ - void buildTable(Table table); - - /** - * @return - */ - ExcelHeadProperty getExcelHeadProperty(); - - /** - * - * @return - */ - boolean needHead(); -} - - diff --git a/src/main/java/com/alibaba/excel/context/GenerateContextImpl.java b/src/main/java/com/alibaba/excel/context/GenerateContextImpl.java deleted file mode 100644 index a79ca3c4..00000000 --- a/src/main/java/com/alibaba/excel/context/GenerateContextImpl.java +++ /dev/null @@ -1,246 +0,0 @@ -package com.alibaba.excel.context; - -import com.alibaba.excel.metadata.*; -import com.alibaba.excel.metadata.CellRange; -import com.alibaba.excel.metadata.Table; -import com.alibaba.excel.metadata.TableStyle; -import com.alibaba.excel.support.ExcelTypeEnum; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.poifs.filesystem.POIFSFileSystem; -import org.apache.poi.ss.usermodel.*; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -/** - * - * @author jipengfei - */ -public class GenerateContextImpl implements GenerateContext { - - private Sheet currentSheet; - - private String currentSheetName; - - private ExcelTypeEnum excelType; - - private Workbook workbook; - - private OutputStream outputStream; - - private Map sheetMap = new ConcurrentHashMap(); - - private Map tableMap = new ConcurrentHashMap(); - - private CellStyle defaultCellStyle; - - private CellStyle currentHeadCellStyle; - - private CellStyle currentContentCellStyle; - - private ExcelHeadProperty excelHeadProperty; - - private boolean needHead = true; - - public GenerateContextImpl(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, - boolean needHead) throws IOException { - if (ExcelTypeEnum.XLS.equals(excelType)) { - if(templateInputStream == null) { - this.workbook = new HSSFWorkbook(); - }else { - this.workbook = new HSSFWorkbook(new POIFSFileSystem(templateInputStream)); - } - } else { - if(templateInputStream == null) { - this.workbook = new SXSSFWorkbook(500); - }else { - this.workbook = new SXSSFWorkbook(new XSSFWorkbook(templateInputStream)); - } - } - this.outputStream = out; - this.defaultCellStyle = buildDefaultCellStyle(); - this.needHead = needHead; - } - - private CellStyle buildDefaultCellStyle() { - CellStyle newCellStyle = this.workbook.createCellStyle(); - Font font = this.workbook.createFont(); - font.setFontName("宋体"); - font.setFontHeightInPoints((short)14); - font.setBold(true); - newCellStyle.setFont(font); - newCellStyle.setWrapText(true); - newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); - newCellStyle.setAlignment(HorizontalAlignment.CENTER); - newCellStyle.setLocked(true); - newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); - newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); - newCellStyle.setBorderBottom(BorderStyle.THIN); - newCellStyle.setBorderLeft(BorderStyle.THIN); - return newCellStyle; - } - - public void buildCurrentSheet(com.alibaba.excel.metadata.Sheet sheet) { - if (sheetMap.containsKey(sheet.getSheetNo())) { - this.currentSheet = sheetMap.get(sheet.getSheetNo()); - } else { - Sheet sheet1 = null; - try { - sheet1 = workbook.getSheetAt(sheet.getSheetNo()); - }catch (Exception e){ - - } - if(sheet1 == null) { - this.currentSheet = workbook.createSheet( - sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + ""); - this.currentSheet.setDefaultColumnWidth(20); - for (Map.Entry entry : sheet.getColumnWidthMap().entrySet()) { - currentSheet.setColumnWidth(entry.getKey(), entry.getValue()); - } - }else { - this.currentSheet = sheet1; - } - sheetMap.put(sheet.getSheetNo(), this.currentSheet); - buildHead(sheet.getHead(), sheet.getClazz()); - buildTableStyle(sheet.getTableStyle()); - if (needHead && excelHeadProperty != null) { - appendHeadToExcel(); - } - } - - } - - private void buildHead(List> head, Class clazz) { - if (head != null || clazz != null) { excelHeadProperty = new ExcelHeadProperty(clazz, head); } - } - - public void appendHeadToExcel() { - if (this.excelHeadProperty.getHead() != null && this.excelHeadProperty.getHead().size() > 0) { - List list = this.excelHeadProperty.getCellRangeModels(); - int n = currentSheet.getLastRowNum(); - if (n > 0) { - n = n + 4; - } - for (CellRange cellRangeModel : list) { - CellRangeAddress cra = new CellRangeAddress(cellRangeModel.getFirstRow() + n, - cellRangeModel.getLastRow() + n, - cellRangeModel.getFirstCol(), cellRangeModel.getLastCol()); - currentSheet.addMergedRegion(cra); - } - int i = n; - for (; i < this.excelHeadProperty.getRowNum() + n; i++) { - Row row = currentSheet.createRow(i); - addOneRowOfHeadDataToExcel(row, this.excelHeadProperty.getHeadByRowNum(i - n)); - } - } - } - - private void addOneRowOfHeadDataToExcel(Row row, List headByRowNum) { - if (headByRowNum != null && headByRowNum.size() > 0) { - for (int i = 0; i < headByRowNum.size(); i++) { - Cell cell = row.createCell(i); - cell.setCellStyle(this.getCurrentHeadCellStyle()); - cell.setCellValue(headByRowNum.get(i)); - } - } - } - - private void buildTableStyle(TableStyle tableStyle) { - if (tableStyle != null) { - CellStyle headStyle = buildDefaultCellStyle(); - if (tableStyle.getTableHeadFont() != null) { - Font font = this.workbook.createFont(); - font.setFontName(tableStyle.getTableHeadFont().getFontName()); - font.setFontHeightInPoints(tableStyle.getTableHeadFont().getFontHeightInPoints()); - font.setBold(tableStyle.getTableHeadFont().isBold()); - headStyle.setFont(font); - } - if (tableStyle.getTableHeadBackGroundColor() != null) { - headStyle.setFillForegroundColor(tableStyle.getTableHeadBackGroundColor().getIndex()); - } - this.currentHeadCellStyle = headStyle; - CellStyle contentStyle = buildDefaultCellStyle(); - if (tableStyle.getTableContentFont() != null) { - Font font = this.workbook.createFont(); - font.setFontName(tableStyle.getTableContentFont().getFontName()); - font.setFontHeightInPoints(tableStyle.getTableContentFont().getFontHeightInPoints()); - font.setBold(tableStyle.getTableContentFont().isBold()); - contentStyle.setFont(font); - } - if (tableStyle.getTableContentBackGroundColor() != null) { - contentStyle.setFillForegroundColor(tableStyle.getTableContentBackGroundColor().getIndex()); - } - this.currentContentCellStyle = contentStyle; - } - } - - public void buildTable(Table table) { - if (!tableMap.containsKey(table.getTableNo())) { - buildHead(table.getHead(), table.getClazz()); - tableMap.put(table.getTableNo(), table); - buildTableStyle(table.getTableStyle()); - if (needHead && excelHeadProperty != null) { - appendHeadToExcel(); - } - } - - } - - public ExcelHeadProperty getExcelHeadProperty() { - return this.excelHeadProperty; - } - - public boolean needHead() { - return this.needHead; - } - - public Sheet getCurrentSheet() { - return currentSheet; - } - - public void setCurrentSheet(Sheet currentSheet) { - this.currentSheet = currentSheet; - } - - public String getCurrentSheetName() { - return currentSheetName; - } - - public void setCurrentSheetName(String currentSheetName) { - this.currentSheetName = currentSheetName; - } - - public ExcelTypeEnum getExcelType() { - return excelType; - } - - public void setExcelType(ExcelTypeEnum excelType) { - this.excelType = excelType; - } - - public OutputStream getOutputStream() { - return outputStream; - } - - public CellStyle getCurrentHeadCellStyle() { - return this.currentHeadCellStyle == null ? defaultCellStyle : this.currentHeadCellStyle; - } - - public CellStyle getCurrentContentStyle() { - return this.currentContentCellStyle; - } - - public Workbook getWorkbook() { - return workbook; - } - -} diff --git a/src/main/java/com/alibaba/excel/context/WriteContext.java b/src/main/java/com/alibaba/excel/context/WriteContext.java new file mode 100644 index 00000000..c3813798 --- /dev/null +++ b/src/main/java/com/alibaba/excel/context/WriteContext.java @@ -0,0 +1,278 @@ +package com.alibaba.excel.context; + +import com.alibaba.excel.metadata.BaseRowModel; +import com.alibaba.excel.metadata.ExcelHeadProperty; +import com.alibaba.excel.metadata.Table; +import com.alibaba.excel.support.ExcelTypeEnum; +import com.alibaba.excel.util.CollectionUtils; +import com.alibaba.excel.util.StyleUtil; +import com.alibaba.excel.util.WorkBookUtil; +import org.apache.poi.ss.usermodel.CellStyle; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.apache.poi.ss.util.CellRangeAddress; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +import static com.alibaba.excel.util.StyleUtil.buildSheetStyle; + +/** + * A context is the main anchorage point of a excel writer. + * + * @author jipengfei + */ +public class WriteContext { + + /*** + * The sheet currently written + */ + private Sheet currentSheet; + + /** + * current param + */ + private com.alibaba.excel.metadata.Sheet currentSheetParam; + + /** + * The sheet currently written's name + */ + private String currentSheetName; + + /** + * + */ + private Table currentTable; + + /** + * Excel type + */ + private ExcelTypeEnum excelType; + + /** + * POI Workbook + */ + private Workbook workbook; + + /** + * Final output stream + */ + private OutputStream outputStream; + + /** + * Written form collection + */ + private Map tableMap = new ConcurrentHashMap(); + + /** + * Cell default style + */ + private CellStyle defaultCellStyle; + + /** + * Current table head style + */ + private CellStyle currentHeadCellStyle; + + /** + * Current table content style + */ + private CellStyle currentContentCellStyle; + + /** + * the header attribute of excel + */ + private ExcelHeadProperty excelHeadProperty; + + private boolean needHead = Boolean.TRUE; + + public WriteContext(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, + boolean needHead) throws IOException { + this.needHead = needHead; + this.outputStream = out; + this.workbook = WorkBookUtil.createWorkBook(templateInputStream, excelType); + this.defaultCellStyle = StyleUtil.buildDefaultCellStyle(this.workbook); + } + + /** + * @param sheet + */ + public void currentSheet(com.alibaba.excel.metadata.Sheet sheet) { + if (null == currentSheetParam || currentSheetParam.getSheetNo() != sheet.getSheetNo()) { + cleanCurrentSheet(); + currentSheetParam = sheet; + try { + this.currentSheet = workbook.getSheetAt(sheet.getSheetNo() - 1); + } catch (Exception e) { + this.currentSheet = WorkBookUtil.createSheet(workbook, sheet); + } + buildSheetStyle(currentSheet, sheet.getColumnWidthMap()); + /** **/ + this.initCurrentSheet(sheet); + } + + } + + private void initCurrentSheet(com.alibaba.excel.metadata.Sheet sheet) { + + /** **/ + initExcelHeadProperty(sheet.getHead(), sheet.getClazz()); + + initTableStyle(sheet.getTableStyle()); + + initTableHead(); + + } + + private void cleanCurrentSheet() { + this.currentSheet = null; + this.currentSheetParam = null; + this.excelHeadProperty = null; + this.currentHeadCellStyle = null; + this.currentContentCellStyle = null; + this.currentTable = null; + + } + + /** + * init excel header + * + * @param head + * @param clazz + */ + private void initExcelHeadProperty(List> head, Class clazz) { + if (head != null || clazz != null) { this.excelHeadProperty = new ExcelHeadProperty(clazz, head); } + } + + public void initTableHead() { + if (needHead && null != excelHeadProperty && !CollectionUtils.isEmpty(excelHeadProperty.getHead())) { + int startRow = currentSheet.getLastRowNum(); + if (startRow > 0) { + startRow += 4; + }else { + startRow = currentSheetParam.getStartRow(); + } + addMergedRegionToCurrentSheet(startRow); + int i = startRow; + for (; i < this.excelHeadProperty.getRowNum() + startRow; i++) { + Row row = WorkBookUtil.createRow(currentSheet, i); + addOneRowOfHeadDataToExcel(row, this.excelHeadProperty.getHeadByRowNum(i - startRow)); + } + } + } + + private void addMergedRegionToCurrentSheet(int startRow) { + for (com.alibaba.excel.metadata.CellRange cellRangeModel : excelHeadProperty.getCellRangeModels()) { + currentSheet.addMergedRegion(new CellRangeAddress(cellRangeModel.getFirstRow() + startRow, + cellRangeModel.getLastRow() + startRow, + cellRangeModel.getFirstCol(), cellRangeModel.getLastCol())); + } + } + + private void addOneRowOfHeadDataToExcel(Row row, List headByRowNum) { + if (headByRowNum != null && headByRowNum.size() > 0) { + for (int i = 0; i < headByRowNum.size(); i++) { + WorkBookUtil.createCell(row, i, getCurrentHeadCellStyle(), headByRowNum.get(i)); + } + } + } + + private void initTableStyle(com.alibaba.excel.metadata.TableStyle tableStyle) { + if (tableStyle != null) { + this.currentHeadCellStyle = StyleUtil.buildCellStyle(this.workbook, tableStyle.getTableHeadFont(), + tableStyle.getTableHeadBackGroundColor()); + this.currentContentCellStyle = StyleUtil.buildCellStyle(this.workbook, tableStyle.getTableContentFont(), + tableStyle.getTableContentBackGroundColor()); + } + } + + private void cleanCurrentTable() { + this.excelHeadProperty = null; + this.currentHeadCellStyle = null; + this.currentContentCellStyle = null; + this.currentTable = null; + + } + + public void currentTable(Table table) { + if (null == currentTable || currentTable.getTableNo() != table.getTableNo()) { + cleanCurrentTable(); + this.currentTable = table; + this.initExcelHeadProperty(table.getHead(), table.getClazz()); + this.initTableStyle(table.getTableStyle()); + this.initTableHead(); + } + + } + + public ExcelHeadProperty getExcelHeadProperty() { + return this.excelHeadProperty; + } + + public boolean needHead() { + return this.needHead; + } + + public Sheet getCurrentSheet() { + return currentSheet; + } + + public void setCurrentSheet(Sheet currentSheet) { + this.currentSheet = currentSheet; + } + + public String getCurrentSheetName() { + return currentSheetName; + } + + public void setCurrentSheetName(String currentSheetName) { + this.currentSheetName = currentSheetName; + } + + public ExcelTypeEnum getExcelType() { + return excelType; + } + + public void setExcelType(ExcelTypeEnum excelType) { + this.excelType = excelType; + } + + public OutputStream getOutputStream() { + return outputStream; + } + + public CellStyle getCurrentHeadCellStyle() { + return this.currentHeadCellStyle == null ? defaultCellStyle : this.currentHeadCellStyle; + } + + public CellStyle getCurrentContentStyle() { + return this.currentContentCellStyle; + } + + public Workbook getWorkbook() { + return workbook; + } + + public com.alibaba.excel.metadata.Sheet getCurrentSheetParam() { + return currentSheetParam; + } + + public void setCurrentSheetParam(com.alibaba.excel.metadata.Sheet currentSheetParam) { + this.currentSheetParam = currentSheetParam; + } + + public Table getCurrentTable() { + return currentTable; + } + + public void setCurrentTable(Table currentTable) { + this.currentTable = currentTable; + } +} + + diff --git a/src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java b/src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java index 7cc50678..7969f77f 100644 --- a/src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java +++ b/src/main/java/com/alibaba/excel/event/AnalysisEventRegisterCenter.java @@ -1,25 +1,29 @@ package com.alibaba.excel.event; - /** + * Event center. * * @author jipengfei */ public interface AnalysisEventRegisterCenter { /** - * @param name 监听名定义 - * @param listener 具体实现 + * Append listener + * + * @param name listener name. + * @param listener Callback method after each row is parsed. */ void appendLister(String name, AnalysisEventListener listener); - /** - * @param event 事件 + * Parse one row to notify all event listeners + * + * @param event parse event */ void notifyListeners(OneRowAnalysisFinishEvent event); /** + * Clean all listeners. */ void cleanAllListeners(); } diff --git a/src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java b/src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java index 9ebdb5a1..9cdc87f1 100644 --- a/src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java +++ b/src/main/java/com/alibaba/excel/event/OneRowAnalysisFinishEvent.java @@ -1,12 +1,26 @@ package com.alibaba.excel.event; +import java.util.ArrayList; +import java.util.List; + /** * @author jipengfei + * @date 2017/07/21 */ public class OneRowAnalysisFinishEvent { - public OneRowAnalysisFinishEvent(Object data) { - this.data = data; + public OneRowAnalysisFinishEvent(Object content) { + this.data = content; + } + + public OneRowAnalysisFinishEvent(String[] content, int length) { + if (content != null) { + List ls = new ArrayList(length); + for (int i = 0; i <= length; i++) { + ls.add(content[i]); + } + data = ls; + } } private Object data; diff --git a/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java b/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java index b2a49004..266cf465 100644 --- a/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java +++ b/src/main/java/com/alibaba/excel/exception/ExcelGenerateException.java @@ -17,5 +17,4 @@ public class ExcelGenerateException extends RuntimeException { public ExcelGenerateException(Throwable cause) { super(cause); } - } diff --git a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java b/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java index 963b9dad..6f4a8059 100644 --- a/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java +++ b/src/main/java/com/alibaba/excel/metadata/BaseRowModel.java @@ -1,10 +1,10 @@ package com.alibaba.excel.metadata; -import org.apache.poi.ss.usermodel.CellStyle; - import java.util.HashMap; import java.util.Map; +import org.apache.poi.ss.usermodel.CellStyle; + /** * Excel基础模型 * @author jipengfei @@ -14,7 +14,7 @@ public class BaseRowModel { /** * 每列样式 */ - private Map cellStyleMap = new HashMap(); + private Map cellStyleMap = new HashMap(); public void addStyle(Integer row, CellStyle cellStyle){ cellStyleMap.put(row,cellStyle); diff --git a/src/main/java/com/alibaba/excel/metadata/CellRange.java b/src/main/java/com/alibaba/excel/metadata/CellRange.java index 6805526e..7fac539b 100644 --- a/src/main/java/com/alibaba/excel/metadata/CellRange.java +++ b/src/main/java/com/alibaba/excel/metadata/CellRange.java @@ -2,6 +2,7 @@ package com.alibaba.excel.metadata; /** * @author jipengfei + * @date 2017/06/02 */ public class CellRange { diff --git a/src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java b/src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java index cc6442f1..8b3ed714 100644 --- a/src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/ExcelColumnProperty.java @@ -6,6 +6,7 @@ import java.util.List; /** * @author jipengfei + * @date 2017/05/31 */ public class ExcelColumnProperty implements Comparable { diff --git a/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java b/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java index 7b15a5ce..628039fb 100644 --- a/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java +++ b/src/main/java/com/alibaba/excel/metadata/ExcelHeadProperty.java @@ -2,29 +2,36 @@ package com.alibaba.excel.metadata; import com.alibaba.excel.annotation.ExcelColumnNum; import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.util.StringUtils; import java.lang.reflect.Field; import java.util.*; /** + * Define the header attribute of excel * * @author jipengfei + * @date 2017/05/31 */ public class ExcelHeadProperty { /** + * Custom class */ private Class headClazz; /** + * A two-dimensional array describing the header */ private List> head = new ArrayList>(); /** + * Attributes described by the header */ private List columnPropertyList = new ArrayList(); /** + * Attributes described by the header */ private Map excelColumnPropertyMap1 = new HashMap(); @@ -55,7 +62,6 @@ public class ExcelHeadProperty { } /** - * * @param f */ private void initOneColumnProperty(Field f) { @@ -103,44 +109,11 @@ public class ExcelHeadProperty { } /** - * * @param columnNum * @return */ public ExcelColumnProperty getExcelColumnProperty(int columnNum) { - ExcelColumnProperty excelColumnProperty = excelColumnPropertyMap1.get(columnNum); - if (excelColumnProperty == null) { - if (head != null && head.size() > columnNum) { - List columnHead = head.get(columnNum); - for (ExcelColumnProperty columnProperty : columnPropertyList) { - if (headEquals(columnHead, columnProperty.getHead())) { - return columnProperty; - } - } - } - } - return excelColumnProperty; - } - - /** - * - * @param columnHead - * @param head - * @return - */ - private boolean headEquals(List columnHead, List head) { - boolean result = true; - if (columnHead == null || head == null || columnHead.size() != head.size()) { - return false; - } else { - for (int i = 0; i < head.size(); i++) { - if (!head.get(i).equals(columnHead.get(i))) { - result = false; - break; - } - } - } - return result; + return excelColumnPropertyMap1.get(columnNum); } public Class getHeadClazz() { @@ -167,20 +140,24 @@ public class ExcelHeadProperty { this.columnPropertyList = columnPropertyList; } + /** + * Calculate all cells that need to be merged + * + * @return cells that need to be merged + */ public List getCellRangeModels() { - List rangs = new ArrayList(); + List cellRanges = new ArrayList(); for (int i = 0; i < head.size(); i++) { - List columnvalues = head.get(i); - for (int j = 0; j < columnvalues.size(); j++) { - int lastRow = getLastRangRow(j, columnvalues.get(j), columnvalues); - int lastColumn = getLastRangColumn(columnvalues.get(j), getHeadByRowNum(j), i); - if (lastRow >= 0 && lastColumn >= 0 && (lastRow > j || lastColumn > i)) { - rangs.add(new CellRange(j, lastRow, i, lastColumn)); + List columnValues = head.get(i); + for (int j = 0; j < columnValues.size(); j++) { + int lastRow = getLastRangNum(j, columnValues.get(j), columnValues); + int lastColumn = getLastRangNum(i, columnValues.get(j), getHeadByRowNum(j)); + if ((lastRow > j || lastColumn > i) && lastRow >= 0 && lastColumn >= 0) { + cellRanges.add(new CellRange(j, lastRow, i, lastColumn)); } - } } - return rangs; + return cellRanges; } public List getHeadByRowNum(int rowNum) { @@ -196,29 +173,36 @@ public class ExcelHeadProperty { } /** - * @param value - * @param headByRowNum - * @param i - * @return + * Get the last consecutive string position + * + * @param j current value position + * @param value value content + * @param values values + * @return the last consecutive string position */ - private int getLastRangColumn(String value, List headByRowNum, int i) { - if (headByRowNum.indexOf(value) < i) { + private int getLastRangNum(int j, String value, List values) { + int lastRow = -1; + if (StringUtils.isEmpty(value)) { return -1; - } else { - return headByRowNum.lastIndexOf(value); } - } - - private int getLastRangRow(int j, String value, List columnvalue) { - - if (columnvalue.indexOf(value) < j) { - return -1; - } - if (value != null && value.equals(columnvalue.get(columnvalue.size() - 1))) { - return getRowNum() - 1; - } else { - return columnvalue.lastIndexOf(value); + for (int i = 0; i < values.size(); i++) { + String current = values.get(i); + if (value.equals(current)) { + if (i >= j) { + lastRow = i; + } else { + //if ij && !value.equals(current) Indicates that the continuous range is exceeded + if (i > j) { + break; + } + } } + return lastRow; + } public int getRowNum() { diff --git a/src/main/java/com/alibaba/excel/metadata/Font.java b/src/main/java/com/alibaba/excel/metadata/Font.java index 45330119..3eea50bf 100644 --- a/src/main/java/com/alibaba/excel/metadata/Font.java +++ b/src/main/java/com/alibaba/excel/metadata/Font.java @@ -3,6 +3,7 @@ package com.alibaba.excel.metadata; /** * * @author jipengfei + * @date 2017/05/24 */ public class Font { diff --git a/src/main/java/com/alibaba/excel/metadata/Sheet.java b/src/main/java/com/alibaba/excel/metadata/Sheet.java index f2828008..ef98b9cc 100644 --- a/src/main/java/com/alibaba/excel/metadata/Sheet.java +++ b/src/main/java/com/alibaba/excel/metadata/Sheet.java @@ -15,6 +15,7 @@ public class Sheet { private int headLineMun; /** + * Starting from 1 */ private int sheetNo; @@ -48,7 +49,7 @@ public class Sheet { /** * */ - private int startRow = -1; + private int startRow = 0; public Sheet(int sheetNo) { diff --git a/src/main/java/com/alibaba/excel/metadata/Table.java b/src/main/java/com/alibaba/excel/metadata/Table.java index a0abeed6..ac9400a7 100644 --- a/src/main/java/com/alibaba/excel/metadata/Table.java +++ b/src/main/java/com/alibaba/excel/metadata/Table.java @@ -4,6 +4,7 @@ import java.util.List; /** * @author jipengfei + * @date 2017/05/16 */ public class Table { /** @@ -16,7 +17,7 @@ public class Table { /** */ - private Integer tableNo; + private int tableNo; /** */ @@ -50,11 +51,11 @@ public class Table { this.head = head; } - public Integer getTableNo() { + public int getTableNo() { return tableNo; } - public void setTableNo(Integer tableNo) { + public void setTableNo(int tableNo) { this.tableNo = tableNo; } } diff --git a/src/main/java/com/alibaba/excel/metadata/TableStyle.java b/src/main/java/com/alibaba/excel/metadata/TableStyle.java index 228019c3..6618197e 100644 --- a/src/main/java/com/alibaba/excel/metadata/TableStyle.java +++ b/src/main/java/com/alibaba/excel/metadata/TableStyle.java @@ -4,6 +4,7 @@ import org.apache.poi.ss.usermodel.IndexedColors; /** * @author jipengfei + * @date 2017/05/24 */ public class TableStyle { diff --git a/src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java b/src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java index b9986037..bea35c7f 100644 --- a/src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java +++ b/src/main/java/com/alibaba/excel/modelbuild/ModelBuildEventListener.java @@ -3,59 +3,37 @@ package com.alibaba.excel.modelbuild; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.event.AnalysisEventListener; import com.alibaba.excel.exception.ExcelGenerateException; -import com.alibaba.excel.metadata.ExcelColumnProperty; import com.alibaba.excel.metadata.ExcelHeadProperty; import com.alibaba.excel.util.TypeUtil; -import org.apache.commons.beanutils.BeanUtils; +import net.sf.cglib.beans.BeanMap; import java.util.List; /** - * * @author jipengfei */ public class ModelBuildEventListener extends AnalysisEventListener { - @Override public void invoke(Object object, AnalysisContext context) { - - - if(context.getExcelHeadProperty() != null && context.getExcelHeadProperty().getHeadClazz()!=null ){ - Object resultModel = buildUserModel(context, (List)object); - context.setCurrentRowAnalysisResult(resultModel); + if (context.getExcelHeadProperty() != null && context.getExcelHeadProperty().getHeadClazz() != null) { + try { + Object resultModel = buildUserModel(context, (List)object); + context.setCurrentRowAnalysisResult(resultModel); + } catch (Exception e) { + throw new ExcelGenerateException(e); + } } - } - - - private Object buildUserModel(AnalysisContext context, List stringList) { + private Object buildUserModel(AnalysisContext context, List stringList) throws Exception { ExcelHeadProperty excelHeadProperty = context.getExcelHeadProperty(); - - Object resultModel; - try { - resultModel = excelHeadProperty.getHeadClazz().newInstance(); - } catch (Exception e) { - throw new ExcelGenerateException(e); - } - if (excelHeadProperty != null) { - for (int i = 0; i < stringList.size(); i++) { - ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty(i); - if (columnProperty != null) { - Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(), - columnProperty.getFormat(),context.use1904WindowDate()); - if (value != null) { - try { - BeanUtils.setProperty(resultModel, columnProperty.getField().getName(), value); - } catch (Exception e) { - throw new ExcelGenerateException( - columnProperty.getField().getName() + " can not set value " + value, e); - } - } - } - } + Object resultModel = excelHeadProperty.getHeadClazz().newInstance(); + if (excelHeadProperty == null) { + return resultModel; } + BeanMap.create(resultModel).putAll( + TypeUtil.getFieldValues(stringList, excelHeadProperty, context.use1904WindowDate())); return resultModel; } diff --git a/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java b/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java index 2f0cc596..f8679ac0 100644 --- a/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java +++ b/src/main/java/com/alibaba/excel/parameter/AnalysisParam.java @@ -17,7 +17,7 @@ public class AnalysisParam { private ExcelTypeEnum excelTypeEnum; /** - * file in + * the POI filesystem that contains the Workbook stream */ private InputStream in; diff --git a/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java b/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java index dd6ca1ee..9f5a57f0 100644 --- a/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java +++ b/src/main/java/com/alibaba/excel/parameter/ExcelWriteParam.java @@ -1,13 +1,14 @@ package com.alibaba.excel.parameter; -import com.alibaba.excel.support.ExcelTypeEnum; - import java.io.OutputStream; +import com.alibaba.excel.support.ExcelTypeEnum; + /** * {@link com.alibaba.excel.ExcelWriter} * * @author jipengfei + * @date 2017/05/15 */ @Deprecated public class ExcelWriteParam { diff --git a/src/main/java/com/alibaba/excel/parameter/GenerateParam.java b/src/main/java/com/alibaba/excel/parameter/GenerateParam.java index 00910e67..9dfccc5f 100644 --- a/src/main/java/com/alibaba/excel/parameter/GenerateParam.java +++ b/src/main/java/com/alibaba/excel/parameter/GenerateParam.java @@ -1,9 +1,9 @@ package com.alibaba.excel.parameter; -import com.alibaba.excel.support.ExcelTypeEnum; - import java.io.OutputStream; +import com.alibaba.excel.support.ExcelTypeEnum; + /** * Created by jipengfei on 17/2/19. */ diff --git a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java index e0102100..57882b90 100644 --- a/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java +++ b/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java @@ -6,16 +6,15 @@ import java.io.IOException; import java.io.InputStream; /** - * * @author jipengfei */ public enum ExcelTypeEnum { - XLS(".xls"), - XLSX(".xlsx"); - // CSV(".csv"); + + XLS(".xls"), XLSX(".xlsx"); + private String value; - private ExcelTypeEnum(String value) { + ExcelTypeEnum(String value) { this.setValue(value); } @@ -26,18 +25,20 @@ public enum ExcelTypeEnum { public void setValue(String value) { this.value = value; } + public static ExcelTypeEnum valueOf(InputStream inputStream){ try { - InputStream in = FileMagic.prepareToCheckMagic(inputStream); - FileMagic fileMagic = FileMagic.valueOf(in); + if (!inputStream.markSupported()) { + return null; + } + FileMagic fileMagic = FileMagic.valueOf(inputStream); if(FileMagic.OLE2.equals(fileMagic)){ return XLS; } if(FileMagic.OOXML.equals(fileMagic)){ return XLSX; } - throw new IllegalArgumentException("excelTypeEnum can not null"); - + return null; } catch (IOException e) { throw new RuntimeException(e); } diff --git a/src/main/java/com/alibaba/excel/util/CollectionUtils.java b/src/main/java/com/alibaba/excel/util/CollectionUtils.java new file mode 100644 index 00000000..3b9025fd --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/CollectionUtils.java @@ -0,0 +1,340 @@ +package com.alibaba.excel.util; + +import java.util.*; + +/** + * Miscellaneous collection utility methods. + * Mainly for internal use within the framework. + * + * @author Juergen Hoeller + * @author Rob Harrop + * @author Arjen Poutsma + * @since 1.1.3 + */ +public abstract class CollectionUtils { + + /** + * Return {@code true} if the supplied Collection is {@code null} or empty. + * Otherwise, return {@code false}. + * @param collection the Collection to check + * @return whether the given Collection is empty + */ + public static boolean isEmpty(Collection collection) { + return (collection == null || collection.isEmpty()); + } + + /** + * Return {@code true} if the supplied Map is {@code null} or empty. + * Otherwise, return {@code false}. + * @param map the Map to check + * @return whether the given Map is empty + */ + public static boolean isEmpty(Map map) { + return (map == null || map.isEmpty()); + } + + /** + * Convert the supplied array into a List. A primitive array gets converted + * into a List of the appropriate wrapper type. + *

NOTE: Generally prefer the standard {@link Arrays#asList} method. + * This {@code arrayToList} method is just meant to deal with an incoming Object + * value that might be an {@code Object[]} or a primitive array at runtime. + *

A {@code null} source value will be converted to an empty List. + * @param source the (potentially primitive) array + * @return the converted List result + * @see ObjectUtils#toObjectArray(Object) + * @see Arrays#asList(Object[]) + */ + @SuppressWarnings("rawtypes") + public static List arrayToList(Object source) { + return Arrays.asList(ObjectUtils.toObjectArray(source)); + } + + /** + * Merge the given array into the given Collection. + * @param array the array to merge (may be {@code null}) + * @param collection the target Collection to merge the array into + */ + @SuppressWarnings("unchecked") + public static void mergeArrayIntoCollection(Object array, Collection collection) { + if (collection == null) { + throw new IllegalArgumentException("Collection must not be null"); + } + Object[] arr = ObjectUtils.toObjectArray(array); + for (Object elem : arr) { + collection.add((E) elem); + } + } + + /** + * Merge the given Properties instance into the given Map, + * copying all properties (key-value pairs) over. + *

Uses {@code Properties.propertyNames()} to even catch + * default properties linked into the original Properties instance. + * @param props the Properties instance to merge (may be {@code null}) + * @param map the target Map to merge the properties into + */ + @SuppressWarnings("unchecked") + public static void mergePropertiesIntoMap(Properties props, Map map) { + if (map == null) { + throw new IllegalArgumentException("Map must not be null"); + } + if (props != null) { + for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { + String key = (String) en.nextElement(); + Object value = props.get(key); + if (value == null) { + // Allow for defaults fallback or potentially overridden accessor... + value = props.getProperty(key); + } + map.put((K) key, (V) value); + } + } + } + + + /** + * Check whether the given Iterator contains the given element. + * @param iterator the Iterator to check + * @param element the element to look for + * @return {@code true} if found, {@code false} else + */ + public static boolean contains(Iterator iterator, Object element) { + if (iterator != null) { + while (iterator.hasNext()) { + Object candidate = iterator.next(); + if (ObjectUtils.nullSafeEquals(candidate, element)) { + return true; + } + } + } + return false; + } + + /** + * Check whether the given Enumeration contains the given element. + * @param enumeration the Enumeration to check + * @param element the element to look for + * @return {@code true} if found, {@code false} else + */ + public static boolean contains(Enumeration enumeration, Object element) { + if (enumeration != null) { + while (enumeration.hasMoreElements()) { + Object candidate = enumeration.nextElement(); + if (ObjectUtils.nullSafeEquals(candidate, element)) { + return true; + } + } + } + return false; + } + + /** + * Check whether the given Collection contains the given element instance. + *

Enforces the given instance to be present, rather than returning + * {@code true} for an equal element as well. + * @param collection the Collection to check + * @param element the element to look for + * @return {@code true} if found, {@code false} else + */ + public static boolean containsInstance(Collection collection, Object element) { + if (collection != null) { + for (Object candidate : collection) { + if (candidate == element) { + return true; + } + } + } + return false; + } + + /** + * Return {@code true} if any element in '{@code candidates}' is + * contained in '{@code source}'; otherwise returns {@code false}. + * @param source the source Collection + * @param candidates the candidates to search for + * @return whether any of the candidates has been found + */ + public static boolean containsAny(Collection source, Collection candidates) { + if (isEmpty(source) || isEmpty(candidates)) { + return false; + } + for (Object candidate : candidates) { + if (source.contains(candidate)) { + return true; + } + } + return false; + } + + /** + * Return the first element in '{@code candidates}' that is contained in + * '{@code source}'. If no element in '{@code candidates}' is present in + * '{@code source}' returns {@code null}. Iteration order is + * {@link Collection} implementation specific. + * @param source the source Collection + * @param candidates the candidates to search for + * @return the first present object, or {@code null} if not found + */ + @SuppressWarnings("unchecked") + public static E findFirstMatch(Collection source, Collection candidates) { + if (isEmpty(source) || isEmpty(candidates)) { + return null; + } + for (Object candidate : candidates) { + if (source.contains(candidate)) { + return (E) candidate; + } + } + return null; + } + + /** + * Find a single value of the given type in the given Collection. + * @param collection the Collection to search + * @param type the type to look for + * @return a value of the given type found if there is a clear match, + * or {@code null} if none or more than one such value found + */ + @SuppressWarnings("unchecked") + public static T findValueOfType(Collection collection, Class type) { + if (isEmpty(collection)) { + return null; + } + T value = null; + for (Object element : collection) { + if (type == null || type.isInstance(element)) { + if (value != null) { + // More than one value found... no clear single value. + return null; + } + value = (T) element; + } + } + return value; + } + + /** + * Find a single value of one of the given types in the given Collection: + * searching the Collection for a value of the first type, then + * searching for a value of the second type, etc. + * @param collection the collection to search + * @param types the types to look for, in prioritized order + * @return a value of one of the given types found if there is a clear match, + * or {@code null} if none or more than one such value found + */ + public static Object findValueOfType(Collection collection, Class[] types) { + if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { + return null; + } + for (Class type : types) { + Object value = findValueOfType(collection, type); + if (value != null) { + return value; + } + } + return null; + } + + /** + * Determine whether the given Collection only contains a single unique object. + * @param collection the Collection to check + * @return {@code true} if the collection contains a single reference or + * multiple references to the same instance, {@code false} else + */ + public static boolean hasUniqueObject(Collection collection) { + if (isEmpty(collection)) { + return false; + } + boolean hasCandidate = false; + Object candidate = null; + for (Object elem : collection) { + if (!hasCandidate) { + hasCandidate = true; + candidate = elem; + } + else if (candidate != elem) { + return false; + } + } + return true; + } + + /** + * Find the common element type of the given Collection, if any. + * @param collection the Collection to check + * @return the common element type, or {@code null} if no clear + * common type has been found (or the collection was empty) + */ + public static Class findCommonElementType(Collection collection) { + if (isEmpty(collection)) { + return null; + } + Class candidate = null; + for (Object val : collection) { + if (val != null) { + if (candidate == null) { + candidate = val.getClass(); + } + else if (candidate != val.getClass()) { + return null; + } + } + } + return candidate; + } + + /** + * Marshal the elements from the given enumeration into an array of the given type. + * Enumeration elements must be assignable to the type of the given array. The array + * returned will be a different instance than the array given. + */ + public static A[] toArray(Enumeration enumeration, A[] array) { + ArrayList elements = new ArrayList(); + while (enumeration.hasMoreElements()) { + elements.add(enumeration.nextElement()); + } + return elements.toArray(array); + } + + /** + * Adapt an enumeration to an iterator. + * @param enumeration the enumeration + * @return the iterator + */ + public static Iterator toIterator(Enumeration enumeration) { + return new EnumerationIterator(enumeration); + } + + + + /** + * Iterator wrapping an Enumeration. + */ + private static class EnumerationIterator implements Iterator { + + private final Enumeration enumeration; + + public EnumerationIterator(Enumeration enumeration) { + this.enumeration = enumeration; + } + + @Override + public boolean hasNext() { + return this.enumeration.hasMoreElements(); + } + + @Override + public E next() { + return this.enumeration.nextElement(); + } + + @Override + public void remove() throws UnsupportedOperationException { + throw new UnsupportedOperationException("Not supported"); + } + } + + +} + diff --git a/src/main/java/com/alibaba/excel/util/IndexValueConverter.java b/src/main/java/com/alibaba/excel/util/IndexValueConverter.java index 90548a7c..af8ac7e1 100644 --- a/src/main/java/com/alibaba/excel/util/IndexValueConverter.java +++ b/src/main/java/com/alibaba/excel/util/IndexValueConverter.java @@ -1,14 +1,15 @@ package com.alibaba.excel.util; -import com.alibaba.excel.metadata.IndexValue; - import java.util.ArrayList; import java.util.List; import java.util.Stack; +import com.alibaba.excel.metadata.IndexValue; + /** * 去除空Cell * @author jipengfei + * @date 2017/04/13 */ public class IndexValueConverter { public static List converter(List i_list) { diff --git a/src/main/java/com/alibaba/excel/util/ObjectUtils.java b/src/main/java/com/alibaba/excel/util/ObjectUtils.java new file mode 100644 index 00000000..8b8556c2 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/ObjectUtils.java @@ -0,0 +1,945 @@ +package com.alibaba.excel.util; + +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Map; + +/** + * Miscellaneous object utility methods. + * + *

Mainly for internal use within the framework. + * + *

Thanks to Alex Ruiz for contributing several enhancements to this class! + * + * @author Juergen Hoeller + * @author Keith Donald + * @author Rod Johnson + * @author Rob Harrop + * @author Chris Beams + * @author Sam Brannen + * @since 19.03.2004 + * @see CollectionUtils + */ +public abstract class ObjectUtils { + + private static final int INITIAL_HASH = 7; + private static final int MULTIPLIER = 31; + + private static final String EMPTY_STRING = ""; + private static final String NULL_STRING = "null"; + private static final String ARRAY_START = "{"; + private static final String ARRAY_END = "}"; + private static final String EMPTY_ARRAY = ARRAY_START + ARRAY_END; + private static final String ARRAY_ELEMENT_SEPARATOR = ", "; + + + /** + * Return whether the given throwable is a checked exception: + * that is, neither a RuntimeException nor an Error. + * @param ex the throwable to check + * @return whether the throwable is a checked exception + * @see Exception + * @see RuntimeException + * @see Error + */ + public static boolean isCheckedException(Throwable ex) { + return !(ex instanceof RuntimeException || ex instanceof Error); + } + + /** + * Check whether the given exception is compatible with the specified + * exception types, as declared in a throws clause. + * @param ex the exception to check + * @param declaredExceptions the exception types declared in the throws clause + * @return whether the given exception is compatible + */ + public static boolean isCompatibleWithThrowsClause(Throwable ex, Class... declaredExceptions) { + if (!isCheckedException(ex)) { + return true; + } + if (declaredExceptions != null) { + for (Class declaredException : declaredExceptions) { + if (declaredException.isInstance(ex)) { + return true; + } + } + } + return false; + } + + /** + * Determine whether the given object is an array: + * either an Object array or a primitive array. + * @param obj the object to check + */ + public static boolean isArray(Object obj) { + return (obj != null && obj.getClass().isArray()); + } + + /** + * Determine whether the given array is empty: + * i.e. {@code null} or of zero length. + * @param array the array to check + * @see #isEmpty(Object) + */ + public static boolean isEmpty(Object[] array) { + return (array == null || array.length == 0); + } + + /** + * Determine whether the given object is empty. + *

This method supports the following object types. + *

+ *

If the given object is non-null and not one of the aforementioned + * supported types, this method returns {@code false}. + * @param obj the object to check + * @return {@code true} if the object is {@code null} or empty + * @since 4.2 + * @see ObjectUtils#isEmpty(Object[]) + * @see StringUtils#hasLength(CharSequence) + * @see StringUtils#isEmpty(Object) + * @see CollectionUtils#isEmpty(Collection) + * @see CollectionUtils#isEmpty(Map) + */ + @SuppressWarnings("rawtypes") + public static boolean isEmpty(Object obj) { + if (obj == null) { + return true; + } + + if (obj instanceof CharSequence) { + return ((CharSequence) obj).length() == 0; + } + if (obj.getClass().isArray()) { + return Array.getLength(obj) == 0; + } + if (obj instanceof Collection) { + return ((Collection) obj).isEmpty(); + } + if (obj instanceof Map) { + return ((Map) obj).isEmpty(); + } + + // else + return false; + } + + /** + * Check whether the given array contains the given element. + * @param array the array to check (may be {@code null}, + * in which case the return value will always be {@code false}) + * @param element the element to check for + * @return whether the element has been found in the given array + */ + public static boolean containsElement(Object[] array, Object element) { + if (array == null) { + return false; + } + for (Object arrayEle : array) { + if (nullSafeEquals(arrayEle, element)) { + return true; + } + } + return false; + } + + /** + * Check whether the given array of enum constants contains a constant with the given name, + * ignoring case when determining a match. + * @param enumValues the enum values to check, typically the product of a call to MyEnum.values() + * @param constant the constant name to find (must not be null or empty string) + * @return whether the constant has been found in the given array + */ + public static boolean containsConstant(Enum[] enumValues, String constant) { + return containsConstant(enumValues, constant, false); + } + + /** + * Check whether the given array of enum constants contains a constant with the given name. + * @param enumValues the enum values to check, typically the product of a call to MyEnum.values() + * @param constant the constant name to find (must not be null or empty string) + * @param caseSensitive whether case is significant in determining a match + * @return whether the constant has been found in the given array + */ + public static boolean containsConstant(Enum[] enumValues, String constant, boolean caseSensitive) { + for (Enum candidate : enumValues) { + if (caseSensitive ? + candidate.toString().equals(constant) : + candidate.toString().equalsIgnoreCase(constant)) { + return true; + } + } + return false; + } + + /** + * Case insensitive alternative to {@link Enum#valueOf(Class, String)}. + * @param the concrete Enum type + * @param enumValues the array of all Enum constants in question, usually per Enum.values() + * @param constant the constant to get the enum value of + * @throws IllegalArgumentException if the given constant is not found in the given array + * of enum values. Use {@link #containsConstant(Enum[], String)} as a guard to avoid this exception. + */ + public static > E caseInsensitiveValueOf(E[] enumValues, String constant) { + for (E candidate : enumValues) { + if (candidate.toString().equalsIgnoreCase(constant)) { + return candidate; + } + } + throw new IllegalArgumentException( + String.format("constant [%s] does not exist in enum type %s", + constant, enumValues.getClass().getComponentType().getName())); + } + + /** + * Append the given object to the given array, returning a new array + * consisting of the input array contents plus the given object. + * @param array the array to append to (can be {@code null}) + * @param obj the object to append + * @return the new array (of the same component type; never {@code null}) + */ + public static A[] addObjectToArray(A[] array, O obj) { + Class compType = Object.class; + if (array != null) { + compType = array.getClass().getComponentType(); + } + else if (obj != null) { + compType = obj.getClass(); + } + int newArrLength = (array != null ? array.length + 1 : 1); + @SuppressWarnings("unchecked") + A[] newArr = (A[]) Array.newInstance(compType, newArrLength); + if (array != null) { + System.arraycopy(array, 0, newArr, 0, array.length); + } + newArr[newArr.length - 1] = obj; + return newArr; + } + + /** + * Convert the given array (which may be a primitive array) to an + * object array (if necessary of primitive wrapper objects). + *

A {@code null} source value will be converted to an + * empty Object array. + * @param source the (potentially primitive) array + * @return the corresponding object array (never {@code null}) + * @throws IllegalArgumentException if the parameter is not an array + */ + public static Object[] toObjectArray(Object source) { + if (source instanceof Object[]) { + return (Object[]) source; + } + if (source == null) { + return new Object[0]; + } + if (!source.getClass().isArray()) { + throw new IllegalArgumentException("Source is not an array: " + source); + } + int length = Array.getLength(source); + if (length == 0) { + return new Object[0]; + } + Class wrapperType = Array.get(source, 0).getClass(); + Object[] newArray = (Object[]) Array.newInstance(wrapperType, length); + for (int i = 0; i < length; i++) { + newArray[i] = Array.get(source, i); + } + return newArray; + } + + + //--------------------------------------------------------------------- + // Convenience methods for content-based equality/hash-code handling + //--------------------------------------------------------------------- + + /** + * Determine if the given objects are equal, returning {@code true} if + * both are {@code null} or {@code false} if only one is {@code null}. + *

Compares arrays with {@code Arrays.equals}, performing an equality + * check based on the array elements rather than the array reference. + * @param o1 first Object to compare + * @param o2 second Object to compare + * @return whether the given objects are equal + * @see Object#equals(Object) + * @see Arrays#equals + */ + public static boolean nullSafeEquals(Object o1, Object o2) { + if (o1 == o2) { + return true; + } + if (o1 == null || o2 == null) { + return false; + } + if (o1.equals(o2)) { + return true; + } + if (o1.getClass().isArray() && o2.getClass().isArray()) { + return arrayEquals(o1, o2); + } + return false; + } + + /** + * Compare the given arrays with {@code Arrays.equals}, performing an equality + * check based on the array elements rather than the array reference. + * @param o1 first array to compare + * @param o2 second array to compare + * @return whether the given objects are equal + * @see #nullSafeEquals(Object, Object) + * @see Arrays#equals + */ + private static boolean arrayEquals(Object o1, Object o2) { + if (o1 instanceof Object[] && o2 instanceof Object[]) { + return Arrays.equals((Object[]) o1, (Object[]) o2); + } + if (o1 instanceof boolean[] && o2 instanceof boolean[]) { + return Arrays.equals((boolean[]) o1, (boolean[]) o2); + } + if (o1 instanceof byte[] && o2 instanceof byte[]) { + return Arrays.equals((byte[]) o1, (byte[]) o2); + } + if (o1 instanceof char[] && o2 instanceof char[]) { + return Arrays.equals((char[]) o1, (char[]) o2); + } + if (o1 instanceof double[] && o2 instanceof double[]) { + return Arrays.equals((double[]) o1, (double[]) o2); + } + if (o1 instanceof float[] && o2 instanceof float[]) { + return Arrays.equals((float[]) o1, (float[]) o2); + } + if (o1 instanceof int[] && o2 instanceof int[]) { + return Arrays.equals((int[]) o1, (int[]) o2); + } + if (o1 instanceof long[] && o2 instanceof long[]) { + return Arrays.equals((long[]) o1, (long[]) o2); + } + if (o1 instanceof short[] && o2 instanceof short[]) { + return Arrays.equals((short[]) o1, (short[]) o2); + } + return false; + } + + /** + * Return as hash code for the given object; typically the value of + * {@code Object#hashCode()}}. If the object is an array, + * this method will delegate to any of the {@code nullSafeHashCode} + * methods for arrays in this class. If the object is {@code null}, + * this method returns 0. + * @see Object#hashCode() + * @see #nullSafeHashCode(Object[]) + * @see #nullSafeHashCode(boolean[]) + * @see #nullSafeHashCode(byte[]) + * @see #nullSafeHashCode(char[]) + * @see #nullSafeHashCode(double[]) + * @see #nullSafeHashCode(float[]) + * @see #nullSafeHashCode(int[]) + * @see #nullSafeHashCode(long[]) + * @see #nullSafeHashCode(short[]) + */ + public static int nullSafeHashCode(Object obj) { + if (obj == null) { + return 0; + } + if (obj.getClass().isArray()) { + if (obj instanceof Object[]) { + return nullSafeHashCode((Object[]) obj); + } + if (obj instanceof boolean[]) { + return nullSafeHashCode((boolean[]) obj); + } + if (obj instanceof byte[]) { + return nullSafeHashCode((byte[]) obj); + } + if (obj instanceof char[]) { + return nullSafeHashCode((char[]) obj); + } + if (obj instanceof double[]) { + return nullSafeHashCode((double[]) obj); + } + if (obj instanceof float[]) { + return nullSafeHashCode((float[]) obj); + } + if (obj instanceof int[]) { + return nullSafeHashCode((int[]) obj); + } + if (obj instanceof long[]) { + return nullSafeHashCode((long[]) obj); + } + if (obj instanceof short[]) { + return nullSafeHashCode((short[]) obj); + } + } + return obj.hashCode(); + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(Object[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (Object element : array) { + hash = MULTIPLIER * hash + nullSafeHashCode(element); + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(boolean[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (boolean element : array) { + hash = MULTIPLIER * hash + hashCode(element); + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(byte[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (byte element : array) { + hash = MULTIPLIER * hash + element; + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(char[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (char element : array) { + hash = MULTIPLIER * hash + element; + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(double[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (double element : array) { + hash = MULTIPLIER * hash + hashCode(element); + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(float[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (float element : array) { + hash = MULTIPLIER * hash + hashCode(element); + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(int[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (int element : array) { + hash = MULTIPLIER * hash + element; + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(long[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (long element : array) { + hash = MULTIPLIER * hash + hashCode(element); + } + return hash; + } + + /** + * Return a hash code based on the contents of the specified array. + * If {@code array} is {@code null}, this method returns 0. + */ + public static int nullSafeHashCode(short[] array) { + if (array == null) { + return 0; + } + int hash = INITIAL_HASH; + for (short element : array) { + hash = MULTIPLIER * hash + element; + } + return hash; + } + + /** + * Return the same value as {@link Boolean#hashCode()}}. + * @see Boolean#hashCode() + */ + public static int hashCode(boolean bool) { + return (bool ? 1231 : 1237); + } + + /** + * Return the same value as {@link Double#hashCode()}}. + * @see Double#hashCode() + */ + public static int hashCode(double dbl) { + return hashCode(Double.doubleToLongBits(dbl)); + } + + /** + * Return the same value as {@link Float#hashCode()}}. + * @see Float#hashCode() + */ + public static int hashCode(float flt) { + return Float.floatToIntBits(flt); + } + + /** + * Return the same value as {@link Long#hashCode()}}. + * @see Long#hashCode() + */ + public static int hashCode(long lng) { + return (int) (lng ^ (lng >>> 32)); + } + + + //--------------------------------------------------------------------- + // Convenience methods for toString output + //--------------------------------------------------------------------- + + /** + * Return a String representation of an object's overall identity. + * @param obj the object (may be {@code null}) + * @return the object's identity as String representation, + * or an empty String if the object was {@code null} + */ + public static String identityToString(Object obj) { + if (obj == null) { + return EMPTY_STRING; + } + return obj.getClass().getName() + "@" + getIdentityHexString(obj); + } + + /** + * Return a hex String form of an object's identity hash code. + * @param obj the object + * @return the object's identity code in hex notation + */ + public static String getIdentityHexString(Object obj) { + return Integer.toHexString(System.identityHashCode(obj)); + } + + /** + * Return a content-based String representation if {@code obj} is + * not {@code null}; otherwise returns an empty String. + *

Differs from {@link #nullSafeToString(Object)} in that it returns + * an empty String rather than "null" for a {@code null} value. + * @param obj the object to build a display String for + * @return a display String representation of {@code obj} + * @see #nullSafeToString(Object) + */ + public static String getDisplayString(Object obj) { + if (obj == null) { + return EMPTY_STRING; + } + return nullSafeToString(obj); + } + + /** + * Determine the class name for the given object. + *

Returns {@code "null"} if {@code obj} is {@code null}. + * @param obj the object to introspect (may be {@code null}) + * @return the corresponding class name + */ + public static String nullSafeClassName(Object obj) { + return (obj != null ? obj.getClass().getName() : NULL_STRING); + } + + /** + * Return a String representation of the specified Object. + *

Builds a String representation of the contents in case of an array. + * Returns {@code "null"} if {@code obj} is {@code null}. + * @param obj the object to build a String representation for + * @return a String representation of {@code obj} + */ + public static String nullSafeToString(Object obj) { + if (obj == null) { + return NULL_STRING; + } + if (obj instanceof String) { + return (String) obj; + } + if (obj instanceof Object[]) { + return nullSafeToString((Object[]) obj); + } + if (obj instanceof boolean[]) { + return nullSafeToString((boolean[]) obj); + } + if (obj instanceof byte[]) { + return nullSafeToString((byte[]) obj); + } + if (obj instanceof char[]) { + return nullSafeToString((char[]) obj); + } + if (obj instanceof double[]) { + return nullSafeToString((double[]) obj); + } + if (obj instanceof float[]) { + return nullSafeToString((float[]) obj); + } + if (obj instanceof int[]) { + return nullSafeToString((int[]) obj); + } + if (obj instanceof long[]) { + return nullSafeToString((long[]) obj); + } + if (obj instanceof short[]) { + return nullSafeToString((short[]) obj); + } + String str = obj.toString(); + return (str != null ? str : EMPTY_STRING); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(Object[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append(String.valueOf(array[i])); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(boolean[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(byte[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(char[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append("'").append(array[i]).append("'"); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(double[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(float[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(int[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(long[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + + /** + * Return a String representation of the contents of the specified array. + *

The String representation consists of a list of the array's elements, + * enclosed in curly braces ({@code "{}"}). Adjacent elements are separated + * by the characters {@code ", "} (a comma followed by a space). Returns + * {@code "null"} if {@code array} is {@code null}. + * @param array the array to build a String representation for + * @return a String representation of {@code array} + */ + public static String nullSafeToString(short[] array) { + if (array == null) { + return NULL_STRING; + } + int length = array.length; + if (length == 0) { + return EMPTY_ARRAY; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + if (i == 0) { + sb.append(ARRAY_START); + } + else { + sb.append(ARRAY_ELEMENT_SEPARATOR); + } + sb.append(array[i]); + } + sb.append(ARRAY_END); + return sb.toString(); + } + +} diff --git a/src/main/java/com/alibaba/excel/util/POITempFile.java b/src/main/java/com/alibaba/excel/util/POITempFile.java index 6382255f..c342968a 100644 --- a/src/main/java/com/alibaba/excel/util/POITempFile.java +++ b/src/main/java/com/alibaba/excel/util/POITempFile.java @@ -5,6 +5,7 @@ import java.io.File; /** * * @author jipengfei + * @date 2017/06/22 */ public class POITempFile { diff --git a/src/main/java/com/alibaba/excel/util/PositionUtils.java b/src/main/java/com/alibaba/excel/util/PositionUtils.java index 37a87dd5..f5f084ac 100644 --- a/src/main/java/com/alibaba/excel/util/PositionUtils.java +++ b/src/main/java/com/alibaba/excel/util/PositionUtils.java @@ -2,6 +2,7 @@ package com.alibaba.excel.util; /** * @author jipengfei + * @date 2017/08/27 */ public class PositionUtils { diff --git a/src/main/java/com/alibaba/excel/util/RowUtil.java b/src/main/java/com/alibaba/excel/util/RowUtil.java new file mode 100644 index 00000000..dc5ea013 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/RowUtil.java @@ -0,0 +1,10 @@ +package com.alibaba.excel.util; + +import org.apache.poi.ss.usermodel.Workbook; + +public class RowUtil { + + //public static int computeNextRow(Workbook workbook,int startRow){ + // + //} +} diff --git a/src/main/java/com/alibaba/excel/util/StringUtils.java b/src/main/java/com/alibaba/excel/util/StringUtils.java new file mode 100644 index 00000000..bd7e12f6 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/StringUtils.java @@ -0,0 +1,1221 @@ +package com.alibaba.excel.util; + +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Enumeration; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.TimeZone; + +/** + * Miscellaneous {@link String} utility methods. + * + *

Mainly for internal use within the framework; consider + * Apache's Commons Lang + * for a more comprehensive suite of {@code String} utilities. + * + *

This class delivers some simple functionality that should really be + * provided by the core Java {@link String} and {@link StringBuilder} + * classes. It also provides easy-to-use methods to convert between + * delimited strings, such as CSV strings, and collections and arrays. + * + * @author Rod Johnson + * @author Juergen Hoeller + * @author Keith Donald + * @author Rob Harrop + * @author Rick Evans + * @author Arjen Poutsma + * @author Sam Brannen + * @author Brian Clozel + * @since 16 April 2001 + */ +public abstract class StringUtils { + + private static final String FOLDER_SEPARATOR = "/"; + + private static final String WINDOWS_FOLDER_SEPARATOR = "\\"; + + private static final String TOP_PATH = ".."; + + private static final String CURRENT_PATH = "."; + + private static final char EXTENSION_SEPARATOR = '.'; + + + //--------------------------------------------------------------------- + // General convenience methods for working with Strings + //--------------------------------------------------------------------- + + /** + * Check whether the given {@code String} is empty. + *

This method accepts any Object as an argument, comparing it to + * {@code null} and the empty String. As a consequence, this method + * will never return {@code true} for a non-null non-String object. + *

The Object signature is useful for general attribute handling code + * that commonly deals with Strings but generally has to iterate over + * Objects since attributes may e.g. be primitive value objects as well. + * @param str the candidate String + * @since 3.2.1 + */ + public static boolean isEmpty(Object str) { + return (str == null || "".equals(str)); + } + + /** + * Check that the given {@code CharSequence} is neither {@code null} nor + * of length 0. + *

Note: this method returns {@code true} for a {@code CharSequence} + * that purely consists of whitespace. + *

+     * StringUtils.hasLength(null) = false
+     * StringUtils.hasLength("") = false
+     * StringUtils.hasLength(" ") = true
+     * StringUtils.hasLength("Hello") = true
+     * 
+ * @param str the {@code CharSequence} to check (may be {@code null}) + * @return {@code true} if the {@code CharSequence} is not {@code null} and has length + * @see #hasText(String) + */ + public static boolean hasLength(CharSequence str) { + return (str != null && str.length() > 0); + } + + /** + * Check that the given {@code String} is neither {@code null} nor of length 0. + *

Note: this method returns {@code true} for a {@code String} that + * purely consists of whitespace. + * @param str the {@code String} to check (may be {@code null}) + * @return {@code true} if the {@code String} is not {@code null} and has length + * @see #hasLength(CharSequence) + * @see #hasText(String) + */ + public static boolean hasLength(String str) { + return (str != null && !str.isEmpty()); + } + + /** + * Check whether the given {@code CharSequence} contains actual text. + *

More specifically, this method returns {@code true} if the + * {@code CharSequence} is not {@code null}, its length is greater than + * 0, and it contains at least one non-whitespace character. + *

+     * StringUtils.hasText(null) = false
+     * StringUtils.hasText("") = false
+     * StringUtils.hasText(" ") = false
+     * StringUtils.hasText("12345") = true
+     * StringUtils.hasText(" 12345 ") = true
+     * 
+ * @param str the {@code CharSequence} to check (may be {@code null}) + * @return {@code true} if the {@code CharSequence} is not {@code null}, + * its length is greater than 0, and it does not contain whitespace only + * @see Character#isWhitespace + */ + public static boolean hasText(CharSequence str) { + return (hasLength(str) && containsText(str)); + } + + /** + * Check whether the given {@code String} contains actual text. + *

More specifically, this method returns {@code true} if the + * {@code String} is not {@code null}, its length is greater than 0, + * and it contains at least one non-whitespace character. + * @param str the {@code String} to check (may be {@code null}) + * @return {@code true} if the {@code String} is not {@code null}, its + * length is greater than 0, and it does not contain whitespace only + * @see #hasText(CharSequence) + */ + public static boolean hasText(String str) { + return (hasLength(str) && containsText(str)); + } + + private static boolean containsText(CharSequence str) { + int strLen = str.length(); + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(str.charAt(i))) { + return true; + } + } + return false; + } + + /** + * Check whether the given {@code CharSequence} contains any whitespace characters. + * @param str the {@code CharSequence} to check (may be {@code null}) + * @return {@code true} if the {@code CharSequence} is not empty and + * contains at least 1 whitespace character + * @see Character#isWhitespace + */ + public static boolean containsWhitespace(CharSequence str) { + if (!hasLength(str)) { + return false; + } + + int strLen = str.length(); + for (int i = 0; i < strLen; i++) { + if (Character.isWhitespace(str.charAt(i))) { + return true; + } + } + return false; + } + + /** + * Check whether the given {@code String} contains any whitespace characters. + * @param str the {@code String} to check (may be {@code null}) + * @return {@code true} if the {@code String} is not empty and + * contains at least 1 whitespace character + * @see #containsWhitespace(CharSequence) + */ + public static boolean containsWhitespace(String str) { + return containsWhitespace((CharSequence) str); + } + + /** + * Trim leading and trailing whitespace from the given {@code String}. + * @param str the {@code String} to check + * @return the trimmed {@code String} + * @see Character#isWhitespace + */ + public static String trimWhitespace(String str) { + if (!hasLength(str)) { + return str; + } + + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { + sb.deleteCharAt(0); + } + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + + /** + * Trim all whitespace from the given {@code String}: + * leading, trailing, and in between characters. + * @param str the {@code String} to check + * @return the trimmed {@code String} + * @see Character#isWhitespace + */ + public static String trimAllWhitespace(String str) { + if (!hasLength(str)) { + return str; + } + + int len = str.length(); + StringBuilder sb = new StringBuilder(str.length()); + for (int i = 0; i < len; i++) { + char c = str.charAt(i); + if (!Character.isWhitespace(c)) { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Trim leading whitespace from the given {@code String}. + * @param str the {@code String} to check + * @return the trimmed {@code String} + * @see Character#isWhitespace + */ + public static String trimLeadingWhitespace(String str) { + if (!hasLength(str)) { + return str; + } + + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) { + sb.deleteCharAt(0); + } + return sb.toString(); + } + + /** + * Trim trailing whitespace from the given {@code String}. + * @param str the {@code String} to check + * @return the trimmed {@code String} + * @see Character#isWhitespace + */ + public static String trimTrailingWhitespace(String str) { + if (!hasLength(str)) { + return str; + } + + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) { + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + + /** + * Trim all occurrences of the supplied leading character from the given {@code String}. + * @param str the {@code String} to check + * @param leadingCharacter the leading character to be trimmed + * @return the trimmed {@code String} + */ + public static String trimLeadingCharacter(String str, char leadingCharacter) { + if (!hasLength(str)) { + return str; + } + + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) { + sb.deleteCharAt(0); + } + return sb.toString(); + } + + /** + * Trim all occurrences of the supplied trailing character from the given {@code String}. + * @param str the {@code String} to check + * @param trailingCharacter the trailing character to be trimmed + * @return the trimmed {@code String} + */ + public static String trimTrailingCharacter(String str, char trailingCharacter) { + if (!hasLength(str)) { + return str; + } + + StringBuilder sb = new StringBuilder(str); + while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) { + sb.deleteCharAt(sb.length() - 1); + } + return sb.toString(); + } + + /** + * Test if the given {@code String} starts with the specified prefix, + * ignoring upper/lower case. + * @param str the {@code String} to check + * @param prefix the prefix to look for + * @see String#startsWith + */ + public static boolean startsWithIgnoreCase(String str, String prefix) { + return (str != null && prefix != null && str.length() >= prefix.length() && + str.regionMatches(true, 0, prefix, 0, prefix.length())); + } + + /** + * Test if the given {@code String} ends with the specified suffix, + * ignoring upper/lower case. + * @param str the {@code String} to check + * @param suffix the suffix to look for + * @see String#endsWith + */ + public static boolean endsWithIgnoreCase(String str, String suffix) { + return (str != null && suffix != null && str.length() >= suffix.length() && + str.regionMatches(true, str.length() - suffix.length(), suffix, 0, suffix.length())); + } + + /** + * Test whether the given string matches the given substring + * at the given index. + * @param str the original string (or StringBuilder) + * @param index the index in the original string to start matching against + * @param substring the substring to match at the given index + */ + public static boolean substringMatch(CharSequence str, int index, CharSequence substring) { + if (index + substring.length() > str.length()) { + return false; + } + for (int i = 0; i < substring.length(); i++) { + if (str.charAt(index + i) != substring.charAt(i)) { + return false; + } + } + return true; + } + + /** + * Count the occurrences of the substring {@code sub} in string {@code str}. + * @param str string to search in + * @param sub string to search for + */ + public static int countOccurrencesOf(String str, String sub) { + if (!hasLength(str) || !hasLength(sub)) { + return 0; + } + + int count = 0; + int pos = 0; + int idx; + while ((idx = str.indexOf(sub, pos)) != -1) { + ++count; + pos = idx + sub.length(); + } + return count; + } + + /** + * Replace all occurrences of a substring within a string with another string. + * @param inString {@code String} to examine + * @param oldPattern {@code String} to replace + * @param newPattern {@code String} to insert + * @return a {@code String} with the replacements + */ + public static String replace(String inString, String oldPattern, String newPattern) { + if (!hasLength(inString) || !hasLength(oldPattern) || newPattern == null) { + return inString; + } + int index = inString.indexOf(oldPattern); + if (index == -1) { + // no occurrence -> can return input as-is + return inString; + } + + int capacity = inString.length(); + if (newPattern.length() > oldPattern.length()) { + capacity += 16; + } + StringBuilder sb = new StringBuilder(capacity); + + int pos = 0; // our position in the old string + int patLen = oldPattern.length(); + while (index >= 0) { + sb.append(inString.substring(pos, index)); + sb.append(newPattern); + pos = index + patLen; + index = inString.indexOf(oldPattern, pos); + } + + // append any characters to the right of a match + sb.append(inString.substring(pos)); + return sb.toString(); + } + + /** + * Delete all occurrences of the given substring. + * @param inString the original {@code String} + * @param pattern the pattern to delete all occurrences of + * @return the resulting {@code String} + */ + public static String delete(String inString, String pattern) { + return replace(inString, pattern, ""); + } + + /** + * Delete any character in a given {@code String}. + * @param inString the original {@code String} + * @param charsToDelete a set of characters to delete. + * E.g. "az\n" will delete 'a's, 'z's and new lines. + * @return the resulting {@code String} + */ + public static String deleteAny(String inString, String charsToDelete) { + if (!hasLength(inString) || !hasLength(charsToDelete)) { + return inString; + } + + StringBuilder sb = new StringBuilder(inString.length()); + for (int i = 0; i < inString.length(); i++) { + char c = inString.charAt(i); + if (charsToDelete.indexOf(c) == -1) { + sb.append(c); + } + } + return sb.toString(); + } + + + //--------------------------------------------------------------------- + // Convenience methods for working with formatted Strings + //--------------------------------------------------------------------- + + /** + * Quote the given {@code String} with single quotes. + * @param str the input {@code String} (e.g. "myString") + * @return the quoted {@code String} (e.g. "'myString'"), + * or {@code null} if the input was {@code null} + */ + public static String quote(String str) { + return (str != null ? "'" + str + "'" : null); + } + + /** + * Turn the given Object into a {@code String} with single quotes + * if it is a {@code String}; keeping the Object as-is else. + * @param obj the input Object (e.g. "myString") + * @return the quoted {@code String} (e.g. "'myString'"), + * or the input object as-is if not a {@code String} + */ + public static Object quoteIfString(Object obj) { + return (obj instanceof String ? quote((String) obj) : obj); + } + + /** + * Unqualify a string qualified by a '.' dot character. For example, + * "this.name.is.qualified", returns "qualified". + * @param qualifiedName the qualified name + */ + public static String unqualify(String qualifiedName) { + return unqualify(qualifiedName, '.'); + } + + /** + * Unqualify a string qualified by a separator character. For example, + * "this:name:is:qualified" returns "qualified" if using a ':' separator. + * @param qualifiedName the qualified name + * @param separator the separator + */ + public static String unqualify(String qualifiedName, char separator) { + return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1); + } + + /** + * Capitalize a {@code String}, changing the first letter to + * upper case as per {@link Character#toUpperCase(char)}. + * No other letters are changed. + * @param str the {@code String} to capitalize + * @return the capitalized {@code String} + */ + public static String capitalize(String str) { + return changeFirstCharacterCase(str, true); + } + + /** + * Uncapitalize a {@code String}, changing the first letter to + * lower case as per {@link Character#toLowerCase(char)}. + * No other letters are changed. + * @param str the {@code String} to uncapitalize + * @return the uncapitalized {@code String} + */ + public static String uncapitalize(String str) { + return changeFirstCharacterCase(str, false); + } + + private static String changeFirstCharacterCase(String str, boolean capitalize) { + if (!hasLength(str)) { + return str; + } + + char baseChar = str.charAt(0); + char updatedChar; + if (capitalize) { + updatedChar = Character.toUpperCase(baseChar); + } + else { + updatedChar = Character.toLowerCase(baseChar); + } + if (baseChar == updatedChar) { + return str; + } + + char[] chars = str.toCharArray(); + chars[0] = updatedChar; + return new String(chars, 0, chars.length); + } + + /** + * Extract the filename from the given Java resource path, + * e.g. {@code "mypath/myfile.txt" -> "myfile.txt"}. + * @param path the file path (may be {@code null}) + * @return the extracted filename, or {@code null} if none + */ + public static String getFilename(String path) { + if (path == null) { + return null; + } + + int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); + return (separatorIndex != -1 ? path.substring(separatorIndex + 1) : path); + } + + /** + * Extract the filename extension from the given Java resource path, + * e.g. "mypath/myfile.txt" -> "txt". + * @param path the file path (may be {@code null}) + * @return the extracted filename extension, or {@code null} if none + */ + public static String getFilenameExtension(String path) { + if (path == null) { + return null; + } + + int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); + if (extIndex == -1) { + return null; + } + + int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); + if (folderIndex > extIndex) { + return null; + } + + return path.substring(extIndex + 1); + } + + /** + * Strip the filename extension from the given Java resource path, + * e.g. "mypath/myfile.txt" -> "mypath/myfile". + * @param path the file path + * @return the path with stripped filename extension + */ + public static String stripFilenameExtension(String path) { + if (path == null) { + return null; + } + + int extIndex = path.lastIndexOf(EXTENSION_SEPARATOR); + if (extIndex == -1) { + return path; + } + + int folderIndex = path.lastIndexOf(FOLDER_SEPARATOR); + if (folderIndex > extIndex) { + return path; + } + + return path.substring(0, extIndex); + } + + /** + * Apply the given relative path to the given Java resource path, + * assuming standard Java folder separation (i.e. "/" separators). + * @param path the path to start from (usually a full file path) + * @param relativePath the relative path to apply + * (relative to the full file path above) + * @return the full file path that results from applying the relative path + */ + public static String applyRelativePath(String path, String relativePath) { + int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR); + if (separatorIndex != -1) { + String newPath = path.substring(0, separatorIndex); + if (!relativePath.startsWith(FOLDER_SEPARATOR)) { + newPath += FOLDER_SEPARATOR; + } + return newPath + relativePath; + } + else { + return relativePath; + } + } + + /** + * Normalize the path by suppressing sequences like "path/.." and + * inner simple dots. + *

The result is convenient for path comparison. For other uses, + * notice that Windows separators ("\") are replaced by simple slashes. + * @param path the original path + * @return the normalized path + */ + public static String cleanPath(String path) { + if (path == null) { + return null; + } + String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR); + + // Strip prefix from path to analyze, to not treat it as part of the + // first path element. This is necessary to correctly parse paths like + // "file:core/../core/io/Resource.class", where the ".." should just + // strip the first "core" directory while keeping the "file:" prefix. + int prefixIndex = pathToUse.indexOf(":"); + String prefix = ""; + if (prefixIndex != -1) { + prefix = pathToUse.substring(0, prefixIndex + 1); + if (prefix.contains("/")) { + prefix = ""; + } + else { + pathToUse = pathToUse.substring(prefixIndex + 1); + } + } + if (pathToUse.startsWith(FOLDER_SEPARATOR)) { + prefix = prefix + FOLDER_SEPARATOR; + pathToUse = pathToUse.substring(1); + } + + String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR); + List pathElements = new LinkedList(); + int tops = 0; + + for (int i = pathArray.length - 1; i >= 0; i--) { + String element = pathArray[i]; + if (CURRENT_PATH.equals(element)) { + // Points to current directory - drop it. + } + else if (TOP_PATH.equals(element)) { + // Registering top path found. + tops++; + } + else { + if (tops > 0) { + // Merging path element with element corresponding to top path. + tops--; + } + else { + // Normal path element found. + pathElements.add(0, element); + } + } + } + + // Remaining top paths need to be retained. + for (int i = 0; i < tops; i++) { + pathElements.add(0, TOP_PATH); + } + + return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR); + } + + /** + * Compare two paths after normalization of them. + * @param path1 first path for comparison + * @param path2 second path for comparison + * @return whether the two paths are equivalent after normalization + */ + public static boolean pathEquals(String path1, String path2) { + return cleanPath(path1).equals(cleanPath(path2)); + } + + /** + * Parse the given {@code localeString} value into a {@link Locale}. + *

This is the inverse operation of {@link Locale#toString Locale's toString}. + * @param localeString the locale {@code String}, following {@code Locale's} + * {@code toString()} format ("en", "en_UK", etc); + * also accepts spaces as separators, as an alternative to underscores + * @return a corresponding {@code Locale} instance, or {@code null} if none + * @throws IllegalArgumentException in case of an invalid locale specification + */ + public static Locale parseLocaleString(String localeString) { + String[] parts = tokenizeToStringArray(localeString, "_ ", false, false); + String language = (parts.length > 0 ? parts[0] : ""); + String country = (parts.length > 1 ? parts[1] : ""); + + validateLocalePart(language); + validateLocalePart(country); + + String variant = ""; + if (parts.length > 2) { + // There is definitely a variant, and it is everything after the country + // code sans the separator between the country code and the variant. + int endIndexOfCountryCode = localeString.indexOf(country, language.length()) + country.length(); + // Strip off any leading '_' and whitespace, what's left is the variant. + variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode)); + if (variant.startsWith("_")) { + variant = trimLeadingCharacter(variant, '_'); + } + } + return (language.length() > 0 ? new Locale(language, country, variant) : null); + } + + private static void validateLocalePart(String localePart) { + for (int i = 0; i < localePart.length(); i++) { + char ch = localePart.charAt(i); + if (ch != ' ' && ch != '_' && ch != '#' && !Character.isLetterOrDigit(ch)) { + throw new IllegalArgumentException( + "Locale part \"" + localePart + "\" contains invalid characters"); + } + } + } + + /** + * Determine the RFC 3066 compliant language tag, + * as used for the HTTP "Accept-Language" header. + * @param locale the Locale to transform to a language tag + * @return the RFC 3066 compliant language tag as {@code String} + */ + public static String toLanguageTag(Locale locale) { + return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : ""); + } + + /** + * Parse the given {@code timeZoneString} value into a {@link TimeZone}. + * @param timeZoneString the time zone {@code String}, following {@link TimeZone#getTimeZone(String)} + * but throwing {@link IllegalArgumentException} in case of an invalid time zone specification + * @return a corresponding {@link TimeZone} instance + * @throws IllegalArgumentException in case of an invalid time zone specification + */ + public static TimeZone parseTimeZoneString(String timeZoneString) { + TimeZone timeZone = TimeZone.getTimeZone(timeZoneString); + if ("GMT".equals(timeZone.getID()) && !timeZoneString.startsWith("GMT")) { + // We don't want that GMT fallback... + throw new IllegalArgumentException("Invalid time zone specification '" + timeZoneString + "'"); + } + return timeZone; + } + + + //--------------------------------------------------------------------- + // Convenience methods for working with String arrays + //--------------------------------------------------------------------- + + /** + * Append the given {@code String} to the given {@code String} array, + * returning a new array consisting of the input array contents plus + * the given {@code String}. + * @param array the array to append to (can be {@code null}) + * @param str the {@code String} to append + * @return the new array (never {@code null}) + */ + public static String[] addStringToArray(String[] array, String str) { + if (ObjectUtils.isEmpty(array)) { + return new String[] {str}; + } + + String[] newArr = new String[array.length + 1]; + System.arraycopy(array, 0, newArr, 0, array.length); + newArr[array.length] = str; + return newArr; + } + + /** + * Concatenate the given {@code String} arrays into one, + * with overlapping array elements included twice. + *

The order of elements in the original arrays is preserved. + * @param array1 the first array (can be {@code null}) + * @param array2 the second array (can be {@code null}) + * @return the new array ({@code null} if both given arrays were {@code null}) + */ + public static String[] concatenateStringArrays(String[] array1, String[] array2) { + if (ObjectUtils.isEmpty(array1)) { + return array2; + } + if (ObjectUtils.isEmpty(array2)) { + return array1; + } + + String[] newArr = new String[array1.length + array2.length]; + System.arraycopy(array1, 0, newArr, 0, array1.length); + System.arraycopy(array2, 0, newArr, array1.length, array2.length); + return newArr; + } + + /** + * Merge the given {@code String} arrays into one, with overlapping + * array elements only included once. + *

The order of elements in the original arrays is preserved + * (with the exception of overlapping elements, which are only + * included on their first occurrence). + * @param array1 the first array (can be {@code null}) + * @param array2 the second array (can be {@code null}) + * @return the new array ({@code null} if both given arrays were {@code null}) + */ + public static String[] mergeStringArrays(String[] array1, String[] array2) { + if (ObjectUtils.isEmpty(array1)) { + return array2; + } + if (ObjectUtils.isEmpty(array2)) { + return array1; + } + + List result = new ArrayList(); + result.addAll(Arrays.asList(array1)); + for (String str : array2) { + if (!result.contains(str)) { + result.add(str); + } + } + return toStringArray(result); + } + + /** + * Turn given source {@code String} array into sorted array. + * @param array the source array + * @return the sorted array (never {@code null}) + */ + public static String[] sortStringArray(String[] array) { + if (ObjectUtils.isEmpty(array)) { + return new String[0]; + } + + Arrays.sort(array); + return array; + } + + /** + * Copy the given {@code Collection} into a {@code String} array. + *

The {@code Collection} must contain {@code String} elements only. + * @param collection the {@code Collection} to copy + * @return the {@code String} array + */ + public static String[] toStringArray(Collection collection) { + if (collection == null) { + return null; + } + + return collection.toArray(new String[collection.size()]); + } + + /** + * Copy the given Enumeration into a {@code String} array. + * The Enumeration must contain {@code String} elements only. + * @param enumeration the Enumeration to copy + * @return the {@code String} array + */ + public static String[] toStringArray(Enumeration enumeration) { + if (enumeration == null) { + return null; + } + + List list = Collections.list(enumeration); + return list.toArray(new String[list.size()]); + } + + /** + * Trim the elements of the given {@code String} array, + * calling {@code String.trim()} on each of them. + * @param array the original {@code String} array + * @return the resulting array (of the same size) with trimmed elements + */ + public static String[] trimArrayElements(String[] array) { + if (ObjectUtils.isEmpty(array)) { + return new String[0]; + } + + String[] result = new String[array.length]; + for (int i = 0; i < array.length; i++) { + String element = array[i]; + result[i] = (element != null ? element.trim() : null); + } + return result; + } + + /** + * Remove duplicate strings from the given array. + *

As of 4.2, it preserves the original order, as it uses a {@link LinkedHashSet}. + * @param array the {@code String} array + * @return an array without duplicates, in natural sort order + */ + public static String[] removeDuplicateStrings(String[] array) { + if (ObjectUtils.isEmpty(array)) { + return array; + } + + Set set = new LinkedHashSet(); + for (String element : array) { + set.add(element); + } + return toStringArray(set); + } + + /** + * Split a {@code String} at the first occurrence of the delimiter. + * Does not include the delimiter in the result. + * @param toSplit the string to split + * @param delimiter to split the string up with + * @return a two element array with index 0 being before the delimiter, and + * index 1 being after the delimiter (neither element includes the delimiter); + * or {@code null} if the delimiter wasn't found in the given input {@code String} + */ + public static String[] split(String toSplit, String delimiter) { + if (!hasLength(toSplit) || !hasLength(delimiter)) { + return null; + } + int offset = toSplit.indexOf(delimiter); + if (offset < 0) { + return null; + } + + String beforeDelimiter = toSplit.substring(0, offset); + String afterDelimiter = toSplit.substring(offset + delimiter.length()); + return new String[] {beforeDelimiter, afterDelimiter}; + } + + /** + * Take an array of strings and split each element based on the given delimiter. + * A {@code Properties} instance is then generated, with the left of the + * delimiter providing the key, and the right of the delimiter providing the value. + *

Will trim both the key and value before adding them to the + * {@code Properties} instance. + * @param array the array to process + * @param delimiter to split each element using (typically the equals symbol) + * @return a {@code Properties} instance representing the array contents, + * or {@code null} if the array to process was {@code null} or empty + */ + public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) { + return splitArrayElementsIntoProperties(array, delimiter, null); + } + + /** + * Take an array of strings and split each element based on the given delimiter. + * A {@code Properties} instance is then generated, with the left of the + * delimiter providing the key, and the right of the delimiter providing the value. + *

Will trim both the key and value before adding them to the + * {@code Properties} instance. + * @param array the array to process + * @param delimiter to split each element using (typically the equals symbol) + * @param charsToDelete one or more characters to remove from each element + * prior to attempting the split operation (typically the quotation mark + * symbol), or {@code null} if no removal should occur + * @return a {@code Properties} instance representing the array contents, + * or {@code null} if the array to process was {@code null} or empty + */ + public static Properties splitArrayElementsIntoProperties( + String[] array, String delimiter, String charsToDelete) { + + if (ObjectUtils.isEmpty(array)) { + return null; + } + + Properties result = new Properties(); + for (String element : array) { + if (charsToDelete != null) { + element = deleteAny(element, charsToDelete); + } + String[] splittedElement = split(element, delimiter); + if (splittedElement == null) { + continue; + } + result.setProperty(splittedElement[0].trim(), splittedElement[1].trim()); + } + return result; + } + + /** + * Tokenize the given {@code String} into a {@code String} array via a + * {@link StringTokenizer}. + *

Trims tokens and omits empty tokens. + *

The given {@code delimiters} string can consist of any number of + * delimiter characters. Each of those characters can be used to separate + * tokens. A delimiter is always a single character; for multi-character + * delimiters, consider using {@link #delimitedListToStringArray}. + * @param str the {@code String} to tokenize + * @param delimiters the delimiter characters, assembled as a {@code String} + * (each of the characters is individually considered as a delimiter) + * @return an array of the tokens + * @see StringTokenizer + * @see String#trim() + * @see #delimitedListToStringArray + */ + public static String[] tokenizeToStringArray(String str, String delimiters) { + return tokenizeToStringArray(str, delimiters, true, true); + } + + /** + * Tokenize the given {@code String} into a {@code String} array via a + * {@link StringTokenizer}. + *

The given {@code delimiters} string can consist of any number of + * delimiter characters. Each of those characters can be used to separate + * tokens. A delimiter is always a single character; for multi-character + * delimiters, consider using {@link #delimitedListToStringArray}. + * @param str the {@code String} to tokenize + * @param delimiters the delimiter characters, assembled as a {@code String} + * (each of the characters is individually considered as a delimiter) + * @param trimTokens trim the tokens via {@link String#trim()} + * @param ignoreEmptyTokens omit empty tokens from the result array + * (only applies to tokens that are empty after trimming; StringTokenizer + * will not consider subsequent delimiters as token in the first place). + * @return an array of the tokens + * @see StringTokenizer + * @see String#trim() + * @see #delimitedListToStringArray + */ + public static String[] tokenizeToStringArray( + String str, String delimiters, boolean trimTokens, boolean ignoreEmptyTokens) { + + if (str == null) { + return null; + } + + StringTokenizer st = new StringTokenizer(str, delimiters); + List tokens = new ArrayList(); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (trimTokens) { + token = token.trim(); + } + if (!ignoreEmptyTokens || token.length() > 0) { + tokens.add(token); + } + } + return toStringArray(tokens); + } + + /** + * Take a {@code String} that is a delimited list and convert it into a + * {@code String} array. + *

A single {@code delimiter} may consist of more than one character, + * but it will still be considered as a single delimiter string, rather + * than as bunch of potential delimiter characters, in contrast to + * {@link #tokenizeToStringArray}. + * @param str the input {@code String} + * @param delimiter the delimiter between elements (this is a single delimiter, + * rather than a bunch individual delimiter characters) + * @return an array of the tokens in the list + * @see #tokenizeToStringArray + */ + public static String[] delimitedListToStringArray(String str, String delimiter) { + return delimitedListToStringArray(str, delimiter, null); + } + + /** + * Take a {@code String} that is a delimited list and convert it into + * a {@code String} array. + *

A single {@code delimiter} may consist of more than one character, + * but it will still be considered as a single delimiter string, rather + * than as bunch of potential delimiter characters, in contrast to + * {@link #tokenizeToStringArray}. + * @param str the input {@code String} + * @param delimiter the delimiter between elements (this is a single delimiter, + * rather than a bunch individual delimiter characters) + * @param charsToDelete a set of characters to delete; useful for deleting unwanted + * line breaks: e.g. "\r\n\f" will delete all new lines and line feeds in a {@code String} + * @return an array of the tokens in the list + * @see #tokenizeToStringArray + */ + public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) { + if (str == null) { + return new String[0]; + } + if (delimiter == null) { + return new String[] {str}; + } + + List result = new ArrayList(); + if ("".equals(delimiter)) { + for (int i = 0; i < str.length(); i++) { + result.add(deleteAny(str.substring(i, i + 1), charsToDelete)); + } + } + else { + int pos = 0; + int delPos; + while ((delPos = str.indexOf(delimiter, pos)) != -1) { + result.add(deleteAny(str.substring(pos, delPos), charsToDelete)); + pos = delPos + delimiter.length(); + } + if (str.length() > 0 && pos <= str.length()) { + // Add rest of String, but not in case of empty input. + result.add(deleteAny(str.substring(pos), charsToDelete)); + } + } + return toStringArray(result); + } + + /** + * Convert a comma delimited list (e.g., a row from a CSV file) into an + * array of strings. + * @param str the input {@code String} + * @return an array of strings, or the empty array in case of empty input + */ + public static String[] commaDelimitedListToStringArray(String str) { + return delimitedListToStringArray(str, ","); + } + + /** + * Convert a comma delimited list (e.g., a row from a CSV file) into a set. + *

Note that this will suppress duplicates, and as of 4.2, the elements in + * the returned set will preserve the original order in a {@link LinkedHashSet}. + * @param str the input {@code String} + * @return a set of {@code String} entries in the list + * @see #removeDuplicateStrings(String[]) + */ + public static Set commaDelimitedListToSet(String str) { + Set set = new LinkedHashSet(); + String[] tokens = commaDelimitedListToStringArray(str); + for (String token : tokens) { + set.add(token); + } + return set; + } + + /** + * Convert a {@link Collection} to a delimited {@code String} (e.g. CSV). + *

Useful for {@code toString()} implementations. + * @param coll the {@code Collection} to convert + * @param delim the delimiter to use (typically a ",") + * @param prefix the {@code String} to start each element with + * @param suffix the {@code String} to end each element with + * @return the delimited {@code String} + */ + public static String collectionToDelimitedString(Collection coll, String delim, String prefix, String suffix) { + if (CollectionUtils.isEmpty(coll)) { + return ""; + } + + StringBuilder sb = new StringBuilder(); + Iterator it = coll.iterator(); + while (it.hasNext()) { + sb.append(prefix).append(it.next()).append(suffix); + if (it.hasNext()) { + sb.append(delim); + } + } + return sb.toString(); + } + + /** + * Convert a {@code Collection} into a delimited {@code String} (e.g. CSV). + *

Useful for {@code toString()} implementations. + * @param coll the {@code Collection} to convert + * @param delim the delimiter to use (typically a ",") + * @return the delimited {@code String} + */ + public static String collectionToDelimitedString(Collection coll, String delim) { + return collectionToDelimitedString(coll, delim, "", ""); + } + + /** + * Convert a {@code Collection} into a delimited {@code String} (e.g., CSV). + *

Useful for {@code toString()} implementations. + * @param coll the {@code Collection} to convert + * @return the delimited {@code String} + */ + public static String collectionToCommaDelimitedString(Collection coll) { + return collectionToDelimitedString(coll, ","); + } + + /** + * Convert a {@code String} array into a delimited {@code String} (e.g. CSV). + *

Useful for {@code toString()} implementations. + * @param arr the array to display + * @param delim the delimiter to use (typically a ",") + * @return the delimited {@code String} + */ + public static String arrayToDelimitedString(Object[] arr, String delim) { + if (ObjectUtils.isEmpty(arr)) { + return ""; + } + if (arr.length == 1) { + return ObjectUtils.nullSafeToString(arr[0]); + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < arr.length; i++) { + if (i > 0) { + sb.append(delim); + } + sb.append(arr[i]); + } + return sb.toString(); + } + + /** + * Convert a {@code String} array into a comma delimited {@code String} + * (i.e., CSV). + *

Useful for {@code toString()} implementations. + * @param arr the array to display + * @return the delimited {@code String} + */ + public static String arrayToCommaDelimitedString(Object[] arr) { + return arrayToDelimitedString(arr, ","); + } + +} diff --git a/src/main/java/com/alibaba/excel/util/StyleUtil.java b/src/main/java/com/alibaba/excel/util/StyleUtil.java new file mode 100644 index 00000000..6fa311c2 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/StyleUtil.java @@ -0,0 +1,68 @@ +package com.alibaba.excel.util; + +import org.apache.poi.ss.usermodel.*; + +import java.util.Map; + +/** + * @author jipengfei + * @date 2017/03/15 + */ +public class StyleUtil { + + /** + * + * @param workbook + * @return + */ + public static CellStyle buildDefaultCellStyle(Workbook workbook) { + CellStyle newCellStyle = workbook.createCellStyle(); + Font font = workbook.createFont(); + font.setFontName("宋体"); + font.setFontHeightInPoints((short)14); + font.setBold(true); + newCellStyle.setFont(font); + newCellStyle.setWrapText(true); + newCellStyle.setVerticalAlignment(VerticalAlignment.CENTER); + newCellStyle.setAlignment(HorizontalAlignment.CENTER); + newCellStyle.setLocked(true); + newCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); + newCellStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); + newCellStyle.setBorderBottom(BorderStyle.THIN); + newCellStyle.setBorderLeft(BorderStyle.THIN); + return newCellStyle; + } + + /** + * + * @param workbook + * @param f + * @param indexedColors + * @return + */ + public static CellStyle buildCellStyle(Workbook workbook, com.alibaba.excel.metadata.Font f, + IndexedColors indexedColors) { + CellStyle cellStyle = buildDefaultCellStyle(workbook); + if (f != null) { + Font font = workbook.createFont(); + font.setFontName(f.getFontName()); + font.setFontHeightInPoints(f.getFontHeightInPoints()); + font.setBold(f.isBold()); + cellStyle.setFont(font); + } + if (indexedColors != null) { + cellStyle.setFillForegroundColor(indexedColors.getIndex()); + } + return cellStyle; + } + + public static Sheet buildSheetStyle(Sheet currentSheet, Map sheetWidthMap){ + currentSheet.setDefaultColumnWidth(20); + for (Map.Entry entry : sheetWidthMap.entrySet()) { + currentSheet.setColumnWidth(entry.getKey(), entry.getValue()); + } + return currentSheet; + } + + +} diff --git a/src/main/java/com/alibaba/excel/util/TypeUtil.java b/src/main/java/com/alibaba/excel/util/TypeUtil.java index 564bf2e5..a04e874d 100644 --- a/src/main/java/com/alibaba/excel/util/TypeUtil.java +++ b/src/main/java/com/alibaba/excel/util/TypeUtil.java @@ -1,27 +1,30 @@ package com.alibaba.excel.util; +import com.alibaba.excel.metadata.ExcelColumnProperty; +import com.alibaba.excel.metadata.ExcelHeadProperty; +import net.sf.cglib.beans.BeanMap; import org.apache.poi.hssf.usermodel.HSSFDateUtil; import java.lang.reflect.Field; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author jipengfei + * @date 2017/03/15 */ public class TypeUtil { - private static List DATE_FORMAT_LIST = new ArrayList(4); + private static List DATE_FORMAT_LIST = new ArrayList(4); static { - DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")); - DATE_FORMAT_LIST.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); + DATE_FORMAT_LIST.add("yyyy/MM/dd HH:mm:ss"); + DATE_FORMAT_LIST.add("yyyy-MM-dd HH:mm:ss"); + DATE_FORMAT_LIST.add("yyyyMMdd HH:mm:ss"); } private static int getCountOfChar(String value, char c) { @@ -39,9 +42,9 @@ public class TypeUtil { } public static Object convert(String value, Field field, String format, boolean us) { - if (isNotEmpty(value)) { - if (String.class.equals(field.getType())) { - return TypeUtil.formatFloat(value); + if (!StringUtils.isEmpty(value)) { + if (Float.class.equals(field.getType())) { + return Float.parseFloat(value); } if (Integer.class.equals(field.getType()) || int.class.equals(field.getType())) { return Integer.parseInt(value); @@ -80,6 +83,9 @@ public class TypeUtil { if (BigDecimal.class.equals(field.getType())) { return new BigDecimal(value); } + if(String.class.equals(field.getType())){ + return formatFloat(value); + } } return null; @@ -106,6 +112,18 @@ public class TypeUtil { return false; } + public static Boolean isNum(Object cellValue) { + if (cellValue instanceof Integer + || cellValue instanceof Double + || cellValue instanceof Short + || cellValue instanceof Long + || cellValue instanceof Float + || cellValue instanceof BigDecimal) { + return true; + } + return false; + } + public static String getDefaultDateString(Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.format(date); @@ -113,9 +131,9 @@ public class TypeUtil { } public static Date getSimpleDateFormatDate(String value, String format) { - if (isNotEmpty(value)) { + if (!StringUtils.isEmpty(value)) { Date date = null; - if (isNotEmpty(format)) { + if (!StringUtils.isEmpty(format)) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); try { date = simpleDateFormat.parse(value); @@ -123,9 +141,10 @@ public class TypeUtil { } catch (ParseException e) { } } - for (SimpleDateFormat dateFormat : DATE_FORMAT_LIST) { + for (String dateFormat : DATE_FORMAT_LIST) { try { - date = dateFormat.parse(value); + SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); + date = simpleDateFormat.parse(value); } catch (ParseException e) { } if (date != null) { @@ -140,16 +159,6 @@ public class TypeUtil { } - public static Boolean isNotEmpty(String value) { - if (value == null) { - return false; - } - if (value.trim().equals("")) { - return false; - } - return true; - - } public static String formatFloat(String value) { if (null != value && value.contains(".")) { @@ -190,12 +199,40 @@ public class TypeUtil { } public static String formatDate(Date cellValue, String format) { - SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); - + SimpleDateFormat simpleDateFormat; + if(!StringUtils.isEmpty(format)) { + simpleDateFormat = new SimpleDateFormat(format); + }else { + simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + } return simpleDateFormat.format(cellValue); } - public static void main(String[] args) { - System.out.println(new Date().toString()); + public static String getFieldStringValue(BeanMap beanMap, String fieldName, String format) { + String cellValue = null; + Object value = beanMap.get(fieldName); + if (value != null) { + if (value instanceof Date) { + cellValue = TypeUtil.formatDate((Date)value, format); + } else { + cellValue = value.toString(); + } + } + return cellValue; + } + + public static Map getFieldValues(List stringList, ExcelHeadProperty excelHeadProperty, Boolean use1904WindowDate) { + Map map = new HashMap(); + for (int i = 0; i < stringList.size(); i++) { + ExcelColumnProperty columnProperty = excelHeadProperty.getExcelColumnProperty(i); + if (columnProperty != null) { + Object value = TypeUtil.convert(stringList.get(i), columnProperty.getField(), + columnProperty.getFormat(), use1904WindowDate); + if (value != null) { + map.put(columnProperty.getField().getName(),value); + } + } + } + return map; } } diff --git a/src/main/java/com/alibaba/excel/util/WorkBookUtil.java b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java new file mode 100644 index 00000000..55369292 --- /dev/null +++ b/src/main/java/com/alibaba/excel/util/WorkBookUtil.java @@ -0,0 +1,75 @@ +package com.alibaba.excel.util; + +import com.alibaba.excel.support.ExcelTypeEnum; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.poifs.filesystem.POIFSFileSystem; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFWorkbook; + +import java.io.IOException; +import java.io.InputStream; + +import static com.alibaba.excel.util.StyleUtil.buildSheetStyle; + +/** + * + * @author jipengfei + */ +public class WorkBookUtil { + + public static Workbook createWorkBook(InputStream templateInputStream, ExcelTypeEnum excelType) throws IOException { + Workbook workbook; + if (ExcelTypeEnum.XLS.equals(excelType)) { + workbook = (templateInputStream == null) ? new HSSFWorkbook() : new HSSFWorkbook( + new POIFSFileSystem(templateInputStream)); + } else { + workbook = (templateInputStream == null) ? new SXSSFWorkbook(500) : new SXSSFWorkbook( + new XSSFWorkbook(templateInputStream)); + } + return workbook; + } + + public static Sheet createOrGetSheet(Workbook workbook, com.alibaba.excel.metadata.Sheet sheet) { + Sheet sheet1 = null; + try { + try { + sheet1 = workbook.getSheetAt(sheet.getSheetNo()-1); + } catch (Exception e) { + } + if (null == sheet1) { + sheet1 = createSheet(workbook, sheet); + buildSheetStyle(sheet1,sheet.getColumnWidthMap()); + } + } catch (Exception e) { + throw new RuntimeException("constructCurrentSheet error", e); + } + return sheet1; + } + + public static Sheet createSheet(Workbook workbook, com.alibaba.excel.metadata.Sheet sheet) { + return workbook.createSheet(sheet.getSheetName() != null ? sheet.getSheetName() : sheet.getSheetNo() + ""); + } + + public static Row createRow(Sheet sheet, int rowNum) { + return sheet.createRow(rowNum); + } + + public static Cell createCell(Row row, int colNum, CellStyle cellStyle, String cellValue) { + return createCell(row, colNum, cellStyle, cellValue, false); + } + + public static Cell createCell(Row row, int colNum, CellStyle cellStyle, Object cellValue, Boolean isNum) { + Cell cell = row.createCell(colNum); + cell.setCellStyle(cellStyle); + if (null != cellValue) { + if (isNum) { + cell.setCellValue(Double.parseDouble(cellValue.toString())); + } else { + cell.setCellValue(cellValue.toString()); + } + } + return cell; + } + +} diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilder.java b/src/main/java/com/alibaba/excel/write/ExcelBuilder.java index 75acb585..787807ef 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilder.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilder.java @@ -2,30 +2,52 @@ package com.alibaba.excel.write; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Table; -import com.alibaba.excel.support.ExcelTypeEnum; -import java.io.InputStream; -import java.io.OutputStream; import java.util.List; /** - * * @author jipengfei */ public interface ExcelBuilder { - void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead); - - + /** + * workBook increase data + * + * @param data List> or List + * @param startRow Start row number + */ void addContent(List data, int startRow); - + /** + * WorkBook increase data + * + * @param data List> or List + * @param sheetParam Write the sheet + */ void addContent(List data, Sheet sheetParam); - + /** + * WorkBook increase data + * + * @param data List> or List + * @param sheetParam Write the sheet + * @param table Write the table + */ void addContent(List data, Sheet sheetParam, Table table); - + /** + * Creates new cell range. Indexes are zero-based. + * + * @param firstRow Index of first row + * @param lastRow Index of last row (inclusive), must be equal to or larger than {@code firstRow} + * @param firstCol Index of first column + * @param lastCol Index of last column (inclusive), must be equal to or larger than {@code firstCol} + */ + void merge(int firstRow, int lastRow, int firstCol, int lastCol); + + /** + * Close io + */ void finish(); } diff --git a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java index b81b73d8..fd993aa0 100644 --- a/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java +++ b/src/main/java/com/alibaba/excel/write/ExcelBuilderImpl.java @@ -1,38 +1,42 @@ package com.alibaba.excel.write; -import com.alibaba.excel.context.GenerateContext; -import com.alibaba.excel.context.GenerateContextImpl; +import com.alibaba.excel.context.WriteContext; +import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.BaseRowModel; import com.alibaba.excel.metadata.ExcelColumnProperty; import com.alibaba.excel.metadata.Sheet; import com.alibaba.excel.metadata.Table; import com.alibaba.excel.support.ExcelTypeEnum; +import com.alibaba.excel.util.CollectionUtils; import com.alibaba.excel.util.POITempFile; import com.alibaba.excel.util.TypeUtil; -import org.apache.commons.beanutils.BeanUtilsBean; -import org.apache.poi.ss.usermodel.Cell; +import com.alibaba.excel.util.WorkBookUtil; +import net.sf.cglib.beans.BeanMap; +import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.util.CellRangeAddress; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.util.Date; import java.util.List; /** * @author jipengfei + * @date 2017/05/27 */ public class ExcelBuilderImpl implements ExcelBuilder { - private GenerateContext context; + private WriteContext context; - @Override - public void init(InputStream templateInputStream, OutputStream out, ExcelTypeEnum excelType, boolean needHead) { + public ExcelBuilderImpl(InputStream templateInputStream, + OutputStream out, + ExcelTypeEnum excelType, + boolean needHead) { try { //初始化时候创建临时缓存目录,用于规避POI在并发写bug POITempFile.createPOIFilesDirectory(); - - context = new GenerateContextImpl(templateInputStream, out, excelType, needHead); + context = new WriteContext(templateInputStream, out, excelType, needHead); } catch (Exception e) { throw new RuntimeException(e); } @@ -40,115 +44,88 @@ public class ExcelBuilderImpl implements ExcelBuilder { @Override public void addContent(List data, int startRow) { - if (data != null && data.size() > 0) { - int rowNum = context.getCurrentSheet().getLastRowNum(); - if (rowNum == 0) { - Row row = context.getCurrentSheet().getRow(0); - if (row == null) { - if (context.getExcelHeadProperty() == null || !context.needHead()) { - rowNum = -1; - } + if (CollectionUtils.isEmpty(data)) { + return; + } + int rowNum = context.getCurrentSheet().getLastRowNum(); + if (rowNum == 0) { + Row row = context.getCurrentSheet().getRow(0); + if (row == null) { + if (context.getExcelHeadProperty() == null || !context.needHead()) { + rowNum = -1; } } - if (rowNum < startRow) { - rowNum = startRow; - } - for (int i = 0; i < data.size(); i++) { - int n = i + rowNum + 1; - - addOneRowOfDataToExcel(data.get(i), n); - } + } + if (rowNum < startRow) { + rowNum = startRow; + } + for (int i = 0; i < data.size(); i++) { + int n = i + rowNum + 1; + addOneRowOfDataToExcel(data.get(i), n); } } @Override public void addContent(List data, Sheet sheetParam) { - context.buildCurrentSheet(sheetParam); + context.currentSheet(sheetParam); addContent(data, sheetParam.getStartRow()); } @Override public void addContent(List data, Sheet sheetParam, Table table) { - context.buildCurrentSheet(sheetParam); - context.buildTable(table); + context.currentSheet(sheetParam); + context.currentTable(table); addContent(data, sheetParam.getStartRow()); } + @Override + public void merge(int firstRow, int lastRow, int firstCol, int lastCol) { + CellRangeAddress cra = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol); + context.getCurrentSheet().addMergedRegion(cra); + } + @Override public void finish() { try { context.getWorkbook().write(context.getOutputStream()); + context.getWorkbook().close(); } catch (IOException e) { - e.printStackTrace(); + throw new ExcelGenerateException("IO error", e); } } - private void addOneRowOfDataToExcel(List oneRowData, Row row) { - if (oneRowData != null && oneRowData.size() > 0) { - for (int i = 0; i < oneRowData.size(); i++) { - Cell cell = row.createCell(i); - cell.setCellStyle(context.getCurrentContentStyle()); - Object cellValue = oneRowData.get(i); - if (cellValue != null) { - if (cellValue instanceof String) { - cell.setCellValue((String)cellValue); - } else if (cellValue instanceof Integer) { - cell.setCellValue(Double.parseDouble(cellValue.toString())); - } else if (cellValue instanceof Double) { - cell.setCellValue((Double)cellValue); - } else if (cellValue instanceof Short) { - cell.setCellValue((Double.parseDouble(cellValue.toString()))); - } - } else { - cell.setCellValue((String)null); - } - } + private void addBasicTypeToExcel(List oneRowData, Row row) { + if (CollectionUtils.isEmpty(oneRowData)) { + return; + } + for (int i = 0; i < oneRowData.size(); i++) { + Object cellValue = oneRowData.get(i); + WorkBookUtil.createCell(row, i, context.getCurrentContentStyle(), cellValue, TypeUtil.isNum(cellValue)); } } - private void addOneRowOfDataToExcel(Object oneRowData, Row row) { + + private void addJavaObjectToExcel(Object oneRowData, Row row) { int i = 0; + BeanMap beanMap = BeanMap.create(oneRowData); for (ExcelColumnProperty excelHeadProperty : context.getExcelHeadProperty().getColumnPropertyList()) { - Cell cell = row.createCell(i); BaseRowModel baseRowModel = (BaseRowModel)oneRowData; - if (baseRowModel.getStyle(i) != null) { - cell.setCellStyle(baseRowModel.getStyle(i)); - } else { - cell.setCellStyle(context.getCurrentContentStyle()); - } - String cellValue = null; - try { - Object value = BeanUtilsBean.getInstance().getPropertyUtils().getNestedProperty(oneRowData, - excelHeadProperty.getField().getName()); - - if (value instanceof Date) { - cellValue = TypeUtil.formatDate((Date)value, excelHeadProperty.getFormat()); - } else { - cellValue = BeanUtilsBean.getInstance().getConvertUtils().convert(value); - } - } catch (Exception e) { - e.printStackTrace(); - } - if (TypeUtil.isNotEmpty(cellValue)) { - if (TypeUtil.isNum(excelHeadProperty.getField())) { - cell.setCellValue(Double.parseDouble(cellValue)); - } else { - cell.setCellValue(cellValue); - } - } else { - cell.setCellValue(""); - } + String cellValue = TypeUtil.getFieldStringValue(beanMap, excelHeadProperty.getField().getName(), + excelHeadProperty.getFormat()); + CellStyle cellStyle = baseRowModel.getStyle(i) != null ? baseRowModel.getStyle(i) + : context.getCurrentContentStyle(); + WorkBookUtil.createCell(row, i, cellStyle, cellValue, TypeUtil.isNum(excelHeadProperty.getField())); i++; } } private void addOneRowOfDataToExcel(Object oneRowData, int n) { - Row row = context.getCurrentSheet().createRow(n); + Row row = WorkBookUtil.createRow(context.getCurrentSheet(), n); if (oneRowData instanceof List) { - addOneRowOfDataToExcel((List)oneRowData, row); + addBasicTypeToExcel((List)oneRowData, row); } else { - addOneRowOfDataToExcel(oneRowData, row); + addJavaObjectToExcel(oneRowData, row); } } } diff --git a/src/test/java/com/alibaba/easyexcel/test/ReadTest.java b/src/test/java/com/alibaba/easyexcel/test/ReadTest.java new file mode 100644 index 00000000..803a0e00 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/ReadTest.java @@ -0,0 +1,187 @@ +package com.alibaba.easyexcel.test; + +import com.alibaba.easyexcel.test.listen.ExcelListener; +import com.alibaba.easyexcel.test.model.JavaModel; +import com.alibaba.easyexcel.test.model.JavaModel2; +import com.alibaba.easyexcel.test.util.FileUtil; +import com.alibaba.excel.EasyExcelFactory; +import com.alibaba.excel.ExcelReader; +import com.alibaba.excel.metadata.Sheet; +import org.junit.Test; + +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +public class ReadTest { + + + /** + * 07版本excel读数据量少于1千行数据,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void simpleReadListStringV2007() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx"); + List data = EasyExcelFactory.read(inputStream, new Sheet(1, 0)); + inputStream.close(); + print(data); + } + + + /** + * 07版本excel读数据量少于1千行数据自动转成javamodel,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void simpleReadJavaModelV2007() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx"); + List data = EasyExcelFactory.read(inputStream, new Sheet(2, 1,JavaModel.class)); + inputStream.close(); + print(data); + } + + /** + * 07版本excel读数据量大于1千行,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadListStringV2007() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx"); + ExcelListener excelListener = new ExcelListener(); + EasyExcelFactory.readBySax(inputStream, new Sheet(1, 1), excelListener); + inputStream.close(); + + } + /** + * 07版本excel读数据量大于1千行,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadJavaModelV2007() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx"); + ExcelListener excelListener = new ExcelListener(); + EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1,JavaModel.class), excelListener); + inputStream.close(); + } + + /** + * 07版本excel读取sheet + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadSheetsV2007() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2007.xlsx"); + ExcelListener excelListener = new ExcelListener(); + ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener); + List sheets = excelReader.getSheets(); + System.out.println(); + for (Sheet sheet:sheets) { + if(sheet.getSheetNo() ==1) { + excelReader.read(sheet); + }else if(sheet.getSheetNo() ==2){ + sheet.setHeadLineMun(1); + sheet.setClazz(JavaModel.class); + excelReader.read(sheet); + }else if(sheet.getSheetNo() ==3){ + sheet.setHeadLineMun(1); + sheet.setClazz(JavaModel2.class); + excelReader.read(sheet); + } + } + inputStream.close(); + } + + + + /** + * 03版本excel读数据量少于1千行数据,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void simpleReadListStringV2003() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls"); + List data = EasyExcelFactory.read(inputStream, new Sheet(1, 0)); + inputStream.close(); + print(data); + } + + /** + * 03版本excel读数据量少于1千行数据转成javamodel,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void simpleReadJavaModelV2003() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls"); + List data = EasyExcelFactory.read(inputStream, new Sheet(2, 1, JavaModel.class)); + inputStream.close(); + print(data); + } + + /** + * 03版本excel读数据量大于1千行数据,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadListStringV2003() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls"); + ExcelListener excelListener = new ExcelListener(); + EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1), excelListener); + inputStream.close(); + } + + /** + * 03版本excel读数据量大于1千行数据转成javamodel,内部采用回调方法. + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadJavaModelV2003() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls"); + ExcelListener excelListener = new ExcelListener(); + EasyExcelFactory.readBySax(inputStream, new Sheet(2, 1, JavaModel.class), excelListener); + inputStream.close(); + } + + /** + * 00版本excel读取sheet + * + * @throws IOException 简单抛出异常,真实环境需要catch异常,同时在finally中关闭流 + */ + @Test + public void saxReadSheetsV2003() throws IOException { + InputStream inputStream = FileUtil.getResourcesFileInputStream("2003.xls"); + ExcelListener excelListener = new ExcelListener(); + ExcelReader excelReader = EasyExcelFactory.getReader(inputStream,excelListener); + List sheets = excelReader.getSheets(); + System.out.println(); + for (Sheet sheet:sheets) { + if(sheet.getSheetNo() == 1) { + excelReader.read(sheet); + }else { + sheet.setHeadLineMun(2); + sheet.setClazz(JavaModel.class); + excelReader.read(sheet); + } + } + inputStream.close(); + } + + + public void print(List datas){ + int i=0; + for (Object ob:datas) { + System.out.println(i++); + System.out.println(ob); + } + } + +} diff --git a/src/test/java/com/alibaba/easyexcel/test/WriteTest.java b/src/test/java/com/alibaba/easyexcel/test/WriteTest.java new file mode 100644 index 00000000..b13fc9c4 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/WriteTest.java @@ -0,0 +1,155 @@ +package com.alibaba.easyexcel.test; + +import com.alibaba.easyexcel.test.model.JavaModel1; +import com.alibaba.excel.EasyExcelFactory; +import com.alibaba.excel.ExcelWriter; +import com.alibaba.excel.metadata.Sheet; +import com.alibaba.excel.metadata.Table; +import com.alibaba.excel.support.ExcelTypeEnum; +import org.junit.Test; + +import java.io.*; +import java.util.HashMap; +import java.util.Map; + +import static com.alibaba.easyexcel.test.util.DataUtil.*; + +public class WriteTest { + + @Test + public void writeV2007() throws IOException { + OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx"); + ExcelWriter writer = EasyExcelFactory.getWriter(out); + //写第一个sheet, sheet1 数据全是List 无模型映射关系 + Sheet sheet1 = new Sheet(1, 3); + sheet1.setSheetName("第一个sheet"); + + //设置列宽 设置每列的宽度 + Map columnWidth = new HashMap(); + columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000); + sheet1.setColumnWidthMap(columnWidth); + sheet1.setHead(createTestListStringHead()); + //or 设置自适应宽度 + //sheet1.setAutoWidth(Boolean.TRUE); + writer.write1(createTestListObject(), sheet1); + + + + //写第二个sheet sheet2 模型上打有表头的注解,合并单元格 + Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null); + sheet2.setTableStyle(createTableStyle()); + writer.write(createTestListJavaMode(), sheet2); + + + + //写第三个sheet包含多个table情况 + Sheet sheet3 = new Sheet(3, 0); + sheet3.setSheetName("第三个sheet"); + Table table1 = new Table(1); + table1.setHead(createTestListStringHead()); + writer.write1(createTestListObject(), sheet3, table1); + + //写sheet2 模型上打有表头的注解 + Table table2 = new Table(2); + table2.setTableStyle(createTableStyle()); + table2.setClazz(JavaModel1.class); + writer.write(createTestListJavaMode(), sheet3, table2); + + writer.finish(); + out.close(); + + } + + + @Test + public void writeV2007WithTemplate() throws IOException { + InputStream inputStream = new BufferedInputStream(new FileInputStream("/Users/jipengfei/temp.xlsx")); + OutputStream out = new FileOutputStream("/Users/jipengfei/2007.xlsx"); + ExcelWriter writer = EasyExcelFactory.getWriterWithTemp(inputStream,out,ExcelTypeEnum.XLSX,true); + //写第一个sheet, sheet1 数据全是List 无模型映射关系 + Sheet sheet1 = new Sheet(1, 3); + sheet1.setSheetName("第一个sheet"); + sheet1.setStartRow(20); + + //设置列宽 设置每列的宽度 + Map columnWidth = new HashMap(); + columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000); + sheet1.setColumnWidthMap(columnWidth); + sheet1.setHead(createTestListStringHead()); + //or 设置自适应宽度 + //sheet1.setAutoWidth(Boolean.TRUE); + writer.write1(createTestListObject(), sheet1); + + + + //写第二个sheet sheet2 模型上打有表头的注解,合并单元格 + Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null); + sheet2.setTableStyle(createTableStyle()); + sheet2.setStartRow(20); + writer.write(createTestListJavaMode(), sheet2); + + + + //写第三个sheet包含多个table情况 + Sheet sheet3 = new Sheet(3, 0); + sheet3.setSheetName("第三个sheet"); + sheet3.setStartRow(30); + Table table1 = new Table(1); + table1.setHead(createTestListStringHead()); + writer.write1(createTestListObject(), sheet3, table1); + + //写sheet2 模型上打有表头的注解 + Table table2 = new Table(2); + table2.setTableStyle(createTableStyle()); + table2.setClazz(JavaModel1.class); + writer.write(createTestListJavaMode(), sheet3, table2); + + writer.finish(); + out.close(); + + } + + + @Test + public void writeV2003() throws IOException { + OutputStream out = new FileOutputStream("/Users/jipengfei/2003.xls"); + ExcelWriter writer = EasyExcelFactory.getWriter(out, ExcelTypeEnum.XLS,true); + //写第一个sheet, sheet1 数据全是List 无模型映射关系 + Sheet sheet1 = new Sheet(1, 3); + sheet1.setSheetName("第一个sheet"); + + //设置列宽 设置每列的宽度 + Map columnWidth = new HashMap(); + columnWidth.put(0,10000);columnWidth.put(1,40000);columnWidth.put(2,10000);columnWidth.put(3,10000); + sheet1.setColumnWidthMap(columnWidth); + sheet1.setHead(createTestListStringHead()); + //or 设置自适应宽度 + //sheet1.setAutoWidth(Boolean.TRUE); + writer.write1(createTestListObject(), sheet1); + + + + //写第二个sheet sheet2 模型上打有表头的注解,合并单元格 + Sheet sheet2 = new Sheet(2, 3, JavaModel1.class, "第二个sheet", null); + sheet2.setTableStyle(createTableStyle()); + writer.write(createTestListJavaMode(), sheet2); + + + + //写第三个sheet包含多个table情况 + Sheet sheet3 = new Sheet(3, 0); + sheet3.setSheetName("第三个sheet"); + Table table1 = new Table(1); + table1.setHead(createTestListStringHead()); + writer.write1(createTestListObject(), sheet3, table1); + + //写sheet2 模型上打有表头的注解 + Table table2 = new Table(2); + table2.setTableStyle(createTableStyle()); + table2.setClazz(JavaModel1.class); + writer.write(createTestListJavaMode(), sheet3, table2); + + writer.finish(); + out.close(); + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java b/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java new file mode 100644 index 00000000..fd185afd --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/listen/ExcelListener.java @@ -0,0 +1,34 @@ +package com.alibaba.easyexcel.test.listen; + +import com.alibaba.excel.context.AnalysisContext; +import com.alibaba.excel.event.AnalysisEventListener; + +import java.util.ArrayList; +import java.util.List; + +public class ExcelListener extends AnalysisEventListener { + + + private List data = new ArrayList(); + + @Override + public void invoke(Object object, AnalysisContext context) { + System.out.println(context.getCurrentSheet()); + if(data.size()<=100){ + data.add(object); + }else { + doSomething(); + data = new ArrayList(); + } + } + + @Override + public void doAfterAllAnalysed(AnalysisContext context) { + doSomething(); + } + public void doSomething(){ + for (Object o:data) { + System.out.println(o); + } + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/model/JavaModel.java b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel.java new file mode 100644 index 00000000..25b9cfe5 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel.java @@ -0,0 +1,136 @@ +package com.alibaba.easyexcel.test.model; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.metadata.BaseRowModel; + +import java.math.BigDecimal; +import java.util.Date; + +public class JavaModel extends BaseRowModel { + @ExcelProperty(index = 0) + private String str; + + @ExcelProperty(index = 1) + private Float ff; + + @ExcelProperty(index = 2) + private Integer mm; + + @ExcelProperty(index = 3) + private BigDecimal money; + + @ExcelProperty(index = 4) + private Long times; + + @ExcelProperty(index = 5) + private Double activityCode; + + @ExcelProperty(index = 6,format = "yyyy-MM-dd") + private Date date; + + @ExcelProperty(index = 7) + private String lx; + + @ExcelProperty(index = 8) + private String name; + + @ExcelProperty(index = 18) + private String kk; + + public String getStr() { + return str; + } + + + public void setStr(String str) { + this.str = str; + } + + public Float getFf() { + return ff; + } + + public void setFf(Float ff) { + this.ff = ff; + } + + public Integer getMm() { + return mm; + } + + public void setMm(Integer mm) { + this.mm = mm; + } + + public BigDecimal getMoney() { + return money; + } + + public void setMoney(BigDecimal money) { + this.money = money; + } + + public Long getTimes() { + return times; + } + + public void setTimes(Long times) { + this.times = times; + } + + public Double getActivityCode() { + return activityCode; + } + + public void setActivityCode(Double activityCode) { + this.activityCode = activityCode; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getLx() { + return lx; + } + + public void setLx(String lx) { + this.lx = lx; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getKk() { + return kk; + } + + public void setKk(String kk) { + this.kk = kk; + } + + @Override + public String toString() { + return "JavaModel{" + + "str='" + str + '\'' + + ", ff=" + ff + + ", mm=" + mm + + ", money=" + money + + ", times=" + times + + ", activityCode=" + activityCode + + ", date=" + date + + ", lx='" + lx + '\'' + + ", name='" + name + '\'' + + ", kk='" + kk + '\'' + + '}'; + } +} diff --git a/src/test/java/function/model/MultiLineHeadExcelModel.java b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel1.java similarity index 61% rename from src/test/java/function/model/MultiLineHeadExcelModel.java rename to src/test/java/com/alibaba/easyexcel/test/model/JavaModel1.java index 5f0317ab..e19a6f96 100644 --- a/src/test/java/function/model/MultiLineHeadExcelModel.java +++ b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel1.java @@ -1,17 +1,12 @@ -package function.model; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; +package com.alibaba.easyexcel.test.model; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.metadata.BaseRowModel; -/** - * Created by jipengfei on 17/2/19. - */ -public class MultiLineHeadExcelModel extends BaseRowModel { +import java.math.BigDecimal; +import java.util.Date; + +public class JavaModel1 extends BaseRowModel { @ExcelProperty(value = {"表头1","表头1","表头31"},index = 0) private String p1; @@ -22,24 +17,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel { @ExcelProperty(value = {"表头3","表头3","表头3"},index = 2) private int p3; - @ExcelProperty(value = {"表头4","表头4","表头4"},index = 3) + @ExcelProperty(value = {"表头1","表头4","表头4"},index = 3) private long p4; @ExcelProperty(value = {"表头5","表头51","表头52"},index = 4) private String p5; @ExcelProperty(value = {"表头6","表头61","表头611"},index = 5) - private String p6; + private float p6; @ExcelProperty(value = {"表头6","表头61","表头612"},index = 6) - private String p7; + private BigDecimal p7; @ExcelProperty(value = {"表头6","表头62","表头621"},index = 7) - private String p8; + private Date p8; @ExcelProperty(value = {"表头6","表头62","表头622"},index = 8) private String p9; + @ExcelProperty(value = {"表头6","表头62","表头622"},index = 9) + private double p10; + public String getP1() { return p1; } @@ -80,27 +78,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel { this.p5 = p5; } - public String getP6() { + public float getP6() { return p6; } - public void setP6(String p6) { + public void setP6(float p6) { this.p6 = p6; } - public String getP7() { + public BigDecimal getP7() { return p7; } - public void setP7(String p7) { + public void setP7(BigDecimal p7) { this.p7 = p7; } - public String getP8() { + public Date getP8() { return p8; } - public void setP8(String p8) { + public void setP8(Date p8) { this.p8 = p8; } @@ -112,16 +110,27 @@ public class MultiLineHeadExcelModel extends BaseRowModel { this.p9 = p9; } - public static void main(String[] args) { - Class clazz = MultiLineHeadExcelModel.class; - Field[] fields = clazz.getDeclaredFields(); - List> head = new ArrayList>(); - for (int i = 0; i < fields.length ; i++) { - Field f = fields[i]; - ExcelProperty p = f.getAnnotation(ExcelProperty.class); - String[] value =p.value(); - head.add(Arrays.asList(value)); - } - System.out.println(head); + public double getP10() { + return p10; + } + + public void setP10(double p10) { + this.p10 = p10; + } + + @Override + public String toString() { + return "JavaModel1{" + + "p1='" + p1 + '\'' + + ", p2='" + p2 + '\'' + + ", p3=" + p3 + + ", p4=" + p4 + + ", p5='" + p5 + '\'' + + ", p6=" + p6 + + ", p7=" + p7 + + ", p8=" + p8 + + ", p9='" + p9 + '\'' + + ", p10=" + p10 + + '}'; } } diff --git a/src/test/java/com/alibaba/easyexcel/test/model/JavaModel2.java b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel2.java new file mode 100644 index 00000000..baf93fc1 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/model/JavaModel2.java @@ -0,0 +1,136 @@ +package com.alibaba.easyexcel.test.model; + +import com.alibaba.excel.annotation.ExcelProperty; +import com.alibaba.excel.metadata.BaseRowModel; + +import java.math.BigDecimal; +import java.util.Date; + +public class JavaModel2 extends BaseRowModel { + @ExcelProperty(index = 0) + private String str; + + @ExcelProperty(index = 1) + private Float ff; + + @ExcelProperty(index = 2) + private Integer mm; + + @ExcelProperty(index = 3) + private BigDecimal money; + + @ExcelProperty(index = 4) + private Long times; + + @ExcelProperty(index = 5) + private Double activityCode; + + @ExcelProperty(index = 6,format = "yyyy-MM-dd") + private Date date; + + @ExcelProperty(index = 7) + private String lx; + + @ExcelProperty(index = 8) + private String name; + + @ExcelProperty(index = 18) + private String kk; + + public String getStr() { + return str; + } + + + public void setStr(String str) { + this.str = str; + } + + public Float getFf() { + return ff; + } + + public void setFf(Float ff) { + this.ff = ff; + } + + public Integer getMm() { + return mm; + } + + public void setMm(Integer mm) { + this.mm = mm; + } + + public BigDecimal getMoney() { + return money; + } + + public void setMoney(BigDecimal money) { + this.money = money; + } + + public Long getTimes() { + return times; + } + + public void setTimes(Long times) { + this.times = times; + } + + public Double getActivityCode() { + return activityCode; + } + + public void setActivityCode(Double activityCode) { + this.activityCode = activityCode; + } + + public Date getDate() { + return date; + } + + public void setDate(Date date) { + this.date = date; + } + + public String getLx() { + return lx; + } + + public void setLx(String lx) { + this.lx = lx; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getKk() { + return kk; + } + + public void setKk(String kk) { + this.kk = kk; + } + + @Override + public String toString() { + return "JavaModel2{" + + "str='" + str + '\'' + + ", ff=" + ff + + ", mm=" + mm + + ", money=" + money + + ", times=" + times + + ", activityCode=" + activityCode + + ", date=" + date + + ", lx='" + lx + '\'' + + ", name='" + name + '\'' + + ", kk='" + kk + '\'' + + '}'; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java b/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java new file mode 100644 index 00000000..934245e9 --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/util/DataUtil.java @@ -0,0 +1,93 @@ +package com.alibaba.easyexcel.test.util; + +import com.alibaba.easyexcel.test.model.JavaModel1; +import com.alibaba.excel.metadata.Font; +import com.alibaba.excel.metadata.TableStyle; +import org.apache.poi.ss.usermodel.IndexedColors; + +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +public class DataUtil { + + + public static List> createTestListObject() { + List> object = new ArrayList>(); + for (int i = 0; i < 1000; i++) { + List da = new ArrayList(); + da.add("字符串"+i); + da.add(Long.valueOf(187837834l+i)); + da.add(Integer.valueOf(2233+i)); + da.add(Double.valueOf(2233.00+i)); + da.add(Float.valueOf(2233.0f+i)); + da.add(new Date()); + da.add(new BigDecimal("3434343433554545"+i)); + da.add(Short.valueOf((short)i)); + object.add(da); + } + return object; + } + + public static List> createTestListStringHead(){ + //写sheet3 模型上没有注解,表头数据动态传入 + List> head = new ArrayList>(); + List headCoulumn1 = new ArrayList(); + List headCoulumn2 = new ArrayList(); + List headCoulumn3 = new ArrayList(); + List headCoulumn4 = new ArrayList(); + List headCoulumn5 = new ArrayList(); + + headCoulumn1.add("第一列");headCoulumn1.add("第一列");headCoulumn1.add("第一列"); + headCoulumn2.add("第一列");headCoulumn2.add("第一列");headCoulumn2.add("第一列"); + + headCoulumn3.add("第二列");headCoulumn3.add("第二列");headCoulumn3.add("第二列"); + headCoulumn4.add("第三列");headCoulumn4.add("第三列2");headCoulumn4.add("第三列2"); + headCoulumn5.add("第一列");headCoulumn5.add("第3列");headCoulumn5.add("第4列"); + + head.add(headCoulumn1); + head.add(headCoulumn2); + head.add(headCoulumn3); + head.add(headCoulumn4); + head.add(headCoulumn5); + return head; + } + + public static List createTestListJavaMode(){ + List model1s = new ArrayList(); + for (int i = 0; i <10000 ; i++) { + JavaModel1 model1 = new JavaModel1(); + model1.setP1("第一列,第"+i+"行"); + model1.setP2("222"+i); + model1.setP3(33+i); + model1.setP4(44); + model1.setP5("555"); + model1.setP6(666.2f); + model1.setP7(new BigDecimal("454545656343434"+i)); + model1.setP8(new Date()); + model1.setP9("llll9999>&&&&&6666^^^^"); + model1.setP10(1111.77+i); + model1s.add(model1); + } + return model1s; + } + + public static TableStyle createTableStyle() { + TableStyle tableStyle = new TableStyle(); + Font headFont = new Font(); + headFont.setBold(true); + headFont.setFontHeightInPoints((short)22); + headFont.setFontName("楷体"); + tableStyle.setTableHeadFont(headFont); + tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE); + + Font contentFont = new Font(); + contentFont.setBold(true); + contentFont.setFontHeightInPoints((short)22); + contentFont.setFontName("黑体"); + tableStyle.setTableContentFont(contentFont); + tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN); + return tableStyle; + } +} diff --git a/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java b/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java new file mode 100644 index 00000000..60cea7ab --- /dev/null +++ b/src/test/java/com/alibaba/easyexcel/test/util/FileUtil.java @@ -0,0 +1,10 @@ +package com.alibaba.easyexcel.test.util; + +import java.io.InputStream; + +public class FileUtil { + + public static InputStream getResourcesFileInputStream(String fileName) { + return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); + } +} diff --git a/src/test/java/function/listener/ExcelListener.java b/src/test/java/function/listener/ExcelListener.java deleted file mode 100644 index d89f3673..00000000 --- a/src/test/java/function/listener/ExcelListener.java +++ /dev/null @@ -1,93 +0,0 @@ -package function.listener; - -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by jipengfei on 17/3/14. - * 解析监听器, - * 每解析一行会回调invoke()方法。 - * 整个excel解析结束会执行doAfterAllAnalysed()方法 - * - * 下面只是我写的一个样例而已,可以根据自己的逻辑修改该类。 - * - * @author jipengfei - * @date 2017/03/14 - */ -public class ExcelListener extends AnalysisEventListener { - - //自定义用于暂时存储data。 - //可以通过实例获取该值 - private List datas = new ArrayList(); - Sheet sheet; - - private ExcelWriter writer; - - - public void invoke(Object object, AnalysisContext context) { - // context.interrupt(); - - System.out.println("当前表格数" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum()); - System.out.println(object); - datas.add(object);//数据存储到list,供批量处理,或后续自己业务逻辑处理。 - List> ll = new ArrayList>(); - ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); - ObjectOutputStream out = null; - try { - out = new ObjectOutputStream(byteOut); - out.writeObject(object); - ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); - ObjectInputStream in = new ObjectInputStream(byteIn); - - List dest = (List)in.readObject(); - ll.add(dest); - } catch (IOException e) { - e.printStackTrace(); - } catch (ClassNotFoundException e) { - e.printStackTrace(); - } - - // writer.write0(ll, sheet); - doSomething(object);//根据自己业务做处理 - - } - - private void doSomething(Object object) { - //1、入库调用接口 - } - - public void doAfterAllAnalysed(AnalysisContext context) { - // writer.finish(); - // datas.clear();//解析结束销毁不用的资源 - } - - public List getDatas() { - return datas; - } - - public void setDatas(List datas) { - this.datas = datas; - } - - public Sheet getSheet() { - return sheet; - } - - public void setSheet(Sheet sheet) { - this.sheet = sheet; - } - - public ExcelWriter getWriter() { - return writer; - } - - public void setWriter(ExcelWriter writer) { - this.writer = writer; - } -} diff --git a/src/test/java/function/model/ExcelPropertyIndexModel.java b/src/test/java/function/model/ExcelPropertyIndexModel.java deleted file mode 100644 index ad9a95de..00000000 --- a/src/test/java/function/model/ExcelPropertyIndexModel.java +++ /dev/null @@ -1,87 +0,0 @@ -package function.model; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * @author jipengfei - */ -public class ExcelPropertyIndexModel extends BaseRowModel { - - @ExcelProperty(value = "姓名" ,index = 0) - private String name; - - @ExcelProperty(value = "年龄",index = 1) - private String age; - - @ExcelProperty(value = "邮箱",index = 2) - private String email; - - @ExcelProperty(value = "地址",index = 3) - private String address; - - @ExcelProperty(value = "性别",index = 4) - private String sax; - - @ExcelProperty(value = "高度",index = 5) - private String heigh; - - @ExcelProperty(value = "备注",index = 6) - private String last; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getAge() { - return age; - } - - public void setAge(String age) { - this.age = age; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getAddress() { - return address; - } - - public void setAddress(String address) { - this.address = address; - } - - public String getSax() { - return sax; - } - - public void setSax(String sax) { - this.sax = sax; - } - - public String getHeigh() { - return heigh; - } - - public void setHeigh(String heigh) { - this.heigh = heigh; - } - - public String getLast() { - return last; - } - - public void setLast(String last) { - this.last = last; - } -} diff --git a/src/test/java/function/model/LoanInfo.java b/src/test/java/function/model/LoanInfo.java deleted file mode 100644 index f0b7f055..00000000 --- a/src/test/java/function/model/LoanInfo.java +++ /dev/null @@ -1,132 +0,0 @@ -package function.model; - -import java.math.BigDecimal; -import java.util.Date; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * Created by jipengfei on 17/3/28. - * - * @author jipengfei - * @date 2017/03/28 - */ -public class LoanInfo extends BaseRowModel implements Comparable { - @ExcelProperty(index = 0) - private String bankLoanId; - - @ExcelProperty(index = 1) - private Long customerId; - - @ExcelProperty(index = 2,format = "yyyy/MM/dd") - private Date loanDate; - - @ExcelProperty(index = 3) - private BigDecimal quota; - - @ExcelProperty(index = 4) - private String bankInterestRate; - - @ExcelProperty(index = 5) - private Integer loanTerm; - - @ExcelProperty(index = 6,format = "yyyy/MM/dd") - private Date loanEndDate; - - @ExcelProperty(index = 7) - private Date interestPerMonth; - - - - // public String getLoanName() { - // return loanName; - // } - // - // public void setLoanName(String loanName) { - // this.loanName = loanName; - // } - - public Date getLoanDate() { - return loanDate; - } - - public void setLoanDate(Date loanDate) { - this.loanDate = loanDate; - } - - public BigDecimal getQuota() { - return quota; - } - - public void setQuota(BigDecimal quota) { - this.quota = quota; - } - - public String getBankInterestRate() { - return bankInterestRate; - } - - public void setBankInterestRate(String bankInterestRate) { - this.bankInterestRate = bankInterestRate; - } - - public Integer getLoanTerm() { - return loanTerm; - } - - public void setLoanTerm(Integer loanTerm) { - this.loanTerm = loanTerm; - } - - public Date getLoanEndDate() { - return loanEndDate; - } - - public void setLoanEndDate(Date loanEndDate) { - this.loanEndDate = loanEndDate; - } - - public Date getInterestPerMonth() { - return interestPerMonth; - } - - public void setInterestPerMonth(Date interestPerMonth) { - this.interestPerMonth = interestPerMonth; - } - - public String getBankLoanId() { - return bankLoanId; - } - - public void setBankLoanId(String bankLoanId) { - this.bankLoanId = bankLoanId; - } - - public Long getCustomerId() { - return customerId; - } - - public void setCustomerId(Long customerId) { - this.customerId = customerId; - } - - @Override - public String toString() { - return "ExcelLoanInfo{" + - "bankLoanId='" + bankLoanId + '\'' + - ", customerId='" + customerId + '\'' + - ", loanDate=" + loanDate + - ", quota=" + quota + - ", bankInterestRate=" + bankInterestRate + - ", loanTerm=" + loanTerm + - ", loanEndDate=" + loanEndDate + - ", interestPerMonth=" + interestPerMonth + - '}'; - } - - public int compareTo(LoanInfo info) { - boolean before = this.getLoanDate().before(info.getLoanDate()); - return before ? 1 : 0; - } -} \ No newline at end of file diff --git a/src/test/java/function/model/NoAnnModel.java b/src/test/java/function/model/NoAnnModel.java deleted file mode 100644 index 0393eb11..00000000 --- a/src/test/java/function/model/NoAnnModel.java +++ /dev/null @@ -1,44 +0,0 @@ -package function.model; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * @author jipengfei - * @date 2017/05/16 - */ -public class NoAnnModel extends BaseRowModel { - - @ExcelProperty(index = 0) - private String p1; - - @ExcelProperty(index = 1) - private String p2; - - @ExcelProperty(index = 2) - private String p3; - - public String getP1() { - return p1; - } - - public void setP1(String p1) { - this.p1 = p1; - } - - public String getP2() { - return p2; - } - - public void setP2(String p2) { - this.p2 = p2; - } - - public String getP3() { - return p3; - } - - public void setP3(String p3) { - this.p3 = p3; - } -} diff --git a/src/test/java/function/model/OneRowHeadExcelModel.java b/src/test/java/function/model/OneRowHeadExcelModel.java deleted file mode 100644 index 9a879352..00000000 --- a/src/test/java/function/model/OneRowHeadExcelModel.java +++ /dev/null @@ -1,270 +0,0 @@ -package function.model; - -import com.alibaba.excel.annotation.ExcelColumnNum; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * Created by jipengfei on 17/2/18. - */ -public class OneRowHeadExcelModel extends BaseRowModel { - - @ExcelColumnNum(value = 0) - private String p1; - - @ExcelColumnNum(1) - private String p2; - - @ExcelColumnNum(2) - private int p3; - - @ExcelColumnNum(3) - private long p4; - - @ExcelColumnNum(4) - private String p5; - - @ExcelColumnNum(5) - private String p6; - - @ExcelColumnNum(6) - private String p7; - - @ExcelColumnNum(7) - private String p8; - - @ExcelColumnNum(8) - private String p9; - - @ExcelColumnNum(9) - private String p10; - - @ExcelColumnNum(10) - private String p11; - - @ExcelColumnNum(11) - private String p12; - - @ExcelColumnNum(12) - private String p13; - - @ExcelColumnNum(13) - private String p14; - - @ExcelColumnNum(14) - private String p15; - - @ExcelColumnNum(15) - private String p16; - - @ExcelColumnNum(16) - private String p17; - - @ExcelColumnNum(17) - private String p18; - - @ExcelColumnNum(18) - private String p19; - - @ExcelColumnNum(19) - private String p20; - - @ExcelColumnNum(20) - private String p21; - - - - public String getP2() { - return p2; - } - - public void setP2(String p2) { - this.p2 = p2; - } - - public int getP3() { - return p3; - } - - public void setP3(int p3) { - this.p3 = p3; - } - - public long getP4() { - return p4; - } - - public void setP4(long p4) { - this.p4 = p4; - } - - public String getP5() { - return p5; - } - - public void setP5(String p5) { - this.p5 = p5; - } - - public String getP6() { - return p6; - } - - public void setP6(String p6) { - this.p6 = p6; - } - - public String getP7() { - return p7; - } - - public void setP7(String p7) { - this.p7 = p7; - } - - public String getP8() { - return p8; - } - - public void setP8(String p8) { - this.p8 = p8; - } - - public String getP9() { - return p9; - } - - public void setP9(String p9) { - this.p9 = p9; - } - - public String getP10() { - return p10; - } - - public void setP10(String p10) { - this.p10 = p10; - } - - public String getP11() { - return p11; - } - - public void setP11(String p11) { - this.p11 = p11; - } - - public String getP12() { - return p12; - } - - public void setP12(String p12) { - this.p12 = p12; - } - - public String getP13() { - return p13; - } - - public void setP13(String p13) { - this.p13 = p13; - } - - public String getP14() { - return p14; - } - - public void setP14(String p14) { - this.p14 = p14; - } - - public String getP15() { - return p15; - } - - public void setP15(String p15) { - this.p15 = p15; - } - - public String getP16() { - return p16; - } - - public void setP16(String p16) { - this.p16 = p16; - } - - public String getP17() { - return p17; - } - - public void setP17(String p17) { - this.p17 = p17; - } - - public String getP18() { - return p18; - } - - public void setP18(String p18) { - this.p18 = p18; - } - - public String getP19() { - return p19; - } - - public void setP19(String p19) { - this.p19 = p19; - } - - public String getP20() { - return p20; - } - - public void setP20(String p20) { - this.p20 = p20; - } - - public String getP21() { - return p21; - } - - public void setP21(String p21) { - this.p21 = p21; - } - - public String getP1() { - return p1; - } - - public void setP1(String p1) { - this.p1 = p1; - } - - @Override - public String toString() { - return "OneRowHeadExcelModel{" + - "p1='" + p1 + '\'' + - ", p2='" + p2 + '\'' + - ", p3=" + p3 + - ", p4=" + p4 + - ", p5='" + p5 + '\'' + - ", p6='" + p6 + '\'' + - ", p7='" + p7 + '\'' + - ", p8='" + p8 + '\'' + - ", p9='" + p9 + '\'' + - ", p10='" + p10 + '\'' + - ", p11='" + p11 + '\'' + - ", p12='" + p12 + '\'' + - ", p13='" + p13 + '\'' + - ", p14='" + p14 + '\'' + - ", p15='" + p15 + '\'' + - ", p16='" + p16 + '\'' + - ", p17='" + p17 + '\'' + - ", p18='" + p18 + '\'' + - ", p19='" + p19 + '\'' + - ", p20='" + p20 + '\'' + - ", p21='" + p21 + '\'' + - '}'; - } -} diff --git a/src/test/java/function/model/TestModel3.java b/src/test/java/function/model/TestModel3.java deleted file mode 100644 index e87a4ffb..00000000 --- a/src/test/java/function/model/TestModel3.java +++ /dev/null @@ -1,354 +0,0 @@ -package function.model; - -import com.alibaba.excel.annotation.ExcelColumnNum; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * Created by jipengfei on 17/3/19. - * - * @author jipengfei - * @date 2017/03/19 - */ -public class TestModel3 extends BaseRowModel { - - @ExcelColumnNum(0) - private String p1; - - @ExcelColumnNum(1) - private String p2; - - @ExcelColumnNum(2) - private String p3; - - @ExcelColumnNum(3) - private String p4; - - @ExcelColumnNum(4) - private String p5; - - @ExcelColumnNum(5) - private String p6; - - @ExcelColumnNum(6) - private String p7; - - @ExcelColumnNum(7) - private String p8; - - @ExcelColumnNum(8) - private String p9; - - @ExcelColumnNum(9) - private String p10; - - @ExcelColumnNum(10) - private String p11; - - @ExcelColumnNum(11) - private String p12; - - @ExcelColumnNum(12) - private String p13; - - @ExcelColumnNum(13) - private String p14; - - @ExcelColumnNum(14) - private String p15; - - @ExcelColumnNum(15) - private String p16; - - @ExcelColumnNum(16) - private String p17; - - @ExcelColumnNum(17) - private String p18; - - @ExcelColumnNum(18) - private String p19; - - @ExcelColumnNum(19) - private String p20; - - @ExcelColumnNum(20) - private String p21; - - @ExcelColumnNum(21) - private String p22; - - @ExcelColumnNum(22) - private String p23; - - @ExcelColumnNum(23) - private String p24; - - @ExcelColumnNum(24) - private String p25; - - @ExcelColumnNum(25) - private String p26; - - @ExcelColumnNum(26) - private String p27; - - @ExcelColumnNum(27) - private String p28; - - @ExcelColumnNum(28) - private String p29; - - @ExcelColumnNum(29) - private String p30; - - @ExcelColumnNum(30) - private String p31; - - public String getP28() { - return p28; - } - - public String getP30() { - return p30; - } - - public void setP30(String p30) { - this.p30 = p30; - } - - public String getP31() { - return p31; - } - - public void setP31(String p31) { - this.p31 = p31; - } - - public void setP28(String p28) { - this.p28 = p28; - } - - public String getP29() { - return p29; - } - - public void setP29(String p29) { - this.p29 = p29; - } - - public String getP1() { - return p1; - } - - public void setP1(String p1) { - this.p1 = p1; - } - - public String getP2() { - return p2; - } - - public void setP2(String p2) { - this.p2 = p2; - } - - public String getP3() { - return p3; - } - - public void setP3(String p3) { - this.p3 = p3; - } - - public String getP4() { - return p4; - } - - public void setP4(String p4) { - this.p4 = p4; - } - - public String getP5() { - return p5; - } - - public void setP5(String p5) { - this.p5 = p5; - } - - public String getP6() { - return p6; - } - - public void setP6(String p6) { - this.p6 = p6; - } - - public String getP7() { - return p7; - } - - public void setP7(String p7) { - this.p7 = p7; - } - - public String getP8() { - return p8; - } - - public void setP8(String p8) { - this.p8 = p8; - } - - public String getP9() { - return p9; - } - - public void setP9(String p9) { - this.p9 = p9; - } - - public String getP10() { - return p10; - } - - public void setP10(String p10) { - this.p10 = p10; - } - - public String getP11() { - return p11; - } - - public void setP11(String p11) { - this.p11 = p11; - } - - public String getP12() { - return p12; - } - - public void setP12(String p12) { - this.p12 = p12; - } - - public String getP13() { - return p13; - } - - public void setP13(String p13) { - this.p13 = p13; - } - - public String getP14() { - return p14; - } - - public void setP14(String p14) { - this.p14 = p14; - } - - public String getP15() { - return p15; - } - - public void setP15(String p15) { - this.p15 = p15; - } - - public String getP16() { - return p16; - } - - public void setP16(String p16) { - this.p16 = p16; - } - - public String getP17() { - return p17; - } - - public void setP17(String p17) { - this.p17 = p17; - } - - public String getP18() { - return p18; - } - - public void setP18(String p18) { - this.p18 = p18; - } - - public String getP19() { - return p19; - } - - public void setP19(String p19) { - this.p19 = p19; - } - - public String getP20() { - return p20; - } - - public void setP20(String p20) { - this.p20 = p20; - } - - public String getP21() { - return p21; - } - - public void setP21(String p21) { - this.p21 = p21; - } - - public String getP22() { - return p22; - } - - public void setP22(String p22) { - this.p22 = p22; - } - - public String getP23() { - return p23; - } - - public void setP23(String p23) { - this.p23 = p23; - } - - public String getP24() { - return p24; - } - - public void setP24(String p24) { - this.p24 = p24; - } - - public String getP25() { - return p25; - } - - public void setP25(String p25) { - this.p25 = p25; - } - - public String getP26() { - return p26; - } - - public void setP26(String p26) { - this.p26 = p26; - } - - public String getP27() { - return p27; - } - - public void setP27(String p27) { - this.p27 = p27; - } -} diff --git a/src/test/java/function/read/ExelAllDataTypeTest.java b/src/test/java/function/read/ExelAllDataTypeTest.java deleted file mode 100644 index a3240442..00000000 --- a/src/test/java/function/read/ExelAllDataTypeTest.java +++ /dev/null @@ -1,46 +0,0 @@ -package function.read; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Created by jipengfei on 17/3/15. - * - * @author jipengfei - * @date 2017/03/15 - */ -public class ExelAllDataTypeTest extends TestCase { - // 创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List的方式通知监听者 - @Test - public void testExcel2007WithReflectModel() { - InputStream inputStream = getInputStream("test2.xlsx"); - - try { - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener).read(new Sheet(1, 1,null)); - }catch (Exception e){ - }finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/function/read/NumTest3.java b/src/test/java/function/read/NumTest3.java deleted file mode 100644 index b1c8fb0c..00000000 --- a/src/test/java/function/read/NumTest3.java +++ /dev/null @@ -1,45 +0,0 @@ -package function.read; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import function.model.TestModel3; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Created by jipengfei on 17/3/19. - * - * @author jipengfei - * @date 2017/03/19 - */ -public class NumTest3 { - - @Test - public void testExcel2007WithReflectModel() { - InputStream inputStream = getInputStream("test3.xlsx"); - try { - AnalysisEventListener listener = new ExcelListener(); - - new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener).read(new Sheet(1, 1, TestModel3.class)); - } catch (Exception e) { - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/function/read/ReadSheets.java b/src/test/java/function/read/ReadSheets.java deleted file mode 100644 index d5e05b69..00000000 --- a/src/test/java/function/read/ReadSheets.java +++ /dev/null @@ -1,82 +0,0 @@ -package function.read; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import org.junit.Test; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -/** - * Created by jipengfei on 17/3/22. - * - * @author jipengfei - * @date 2017/03/22 - */ -public class ReadSheets { - @Test - public void ReadSheets2007() { - InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx"); - try { - ExcelListener listener = new ExcelListener(); - listener.setSheet(new Sheet(1)); - ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/77.xlsx"), ExcelTypeEnum.XLSX,false); - listener.setWriter(excelWriter); - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet:sheets) { - sheet.setHeadLineMun(1); - reader.read(sheet); - } - // reader.read(new Sheet(1)); - excelWriter.finish(); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void ReadSheets2003() { - InputStream inputStream = getInputStream("2003.xls"); - try { - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener); - reader.read(); - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet:sheets) { - sheet.setHeadLineMun(1); - reader.read(sheet); - } - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/function/read/XLSX2007FunctionTest.java b/src/test/java/function/read/XLSX2007FunctionTest.java deleted file mode 100644 index 8cc66d43..00000000 --- a/src/test/java/function/read/XLSX2007FunctionTest.java +++ /dev/null @@ -1,139 +0,0 @@ -package function.read; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import function.model.OneRowHeadExcelModel; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Created by jipengfei on 17/2/18. - */ -public class XLSX2007FunctionTest extends TestCase { - - //创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List的方式通知监听者 - @Test - public void testExcel2007NoModel() { - InputStream inputStream = getInputStream("2007NoModelBigFile.xlsx"); - try { - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - - reader.read(); - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - @Test - public void testExcel2007NoModel2() { - InputStream inputStream = getInputStream("test4.xlsx"); - try { - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - - reader.read(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - //创建没有自定义模型,但有规定sheet解析器,解析结果以List的方式通知监听者 - @Test - public void testExcel2007WithSheet() { - InputStream inputStream = getInputStream("111.xlsx"); - - try { - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - reader.read(new Sheet(1, 0)); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - //创建需要反射映射模型的解析器,解析结果List Object为自定义的模型 - @Test - public void testExcel2007WithReflectModel() { - InputStream inputStream = getInputStream("2007.xlsx"); - try { - - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - - reader.read(new Sheet(1, 1, OneRowHeadExcelModel.class)); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - @Test - public void testExcel2007MultHeadWithReflectModel() { - InputStream inputStream = getInputStream("2007_1.xlsx"); - - try { - - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - - reader.read(new Sheet(1, 4, OneRowHeadExcelModel.class)); - - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/function/write/ExcelWriteIndexTest.java b/src/test/java/function/write/ExcelWriteIndexTest.java deleted file mode 100644 index 88c88b67..00000000 --- a/src/test/java/function/write/ExcelWriteIndexTest.java +++ /dev/null @@ -1,117 +0,0 @@ -package function.write; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; - -import function.model.ExcelPropertyIndexModel; -import function.model.MultiLineHeadExcelModel; -import org.junit.Test; - -/** - * 测试{@link ExcelProperty#index()} - * - * @author jipengfei - * @date 2017/05/31 - */ -public class ExcelWriteIndexTest { - - @Test - public void test1() throws FileNotFoundException { - OutputStream out = new FileOutputStream("/Users/jipengfei/78.xlsx"); - try { - ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); - //写第一个sheet, sheet1 数据全是List 无模型映射关系 - Sheet sheet1 = new Sheet(1, 0,ExcelPropertyIndexModel.class); - writer.write(getData(), sheet1); - writer.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - @Test - public void test2() throws FileNotFoundException { - OutputStream out = new FileOutputStream("/Users/jipengfei/79.xlsx"); - try { - ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX); - //写第一个sheet, sheet1 数据全是List 无模型映射关系 - Sheet sheet1 = new Sheet(1, 3,MultiLineHeadExcelModel.class); - writer.write(getModeldatas(), sheet1); - writer.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - public List getData() { - List datas = new ArrayList(); - ExcelPropertyIndexModel model = new ExcelPropertyIndexModel(); - model.setAddress("杭州"); - model.setAge("11"); - model.setEmail("7827323@qq.com"); - model.setSax("男"); - model.setHeigh("1123"); - datas.add(model); - return datas; - } - private List getModeldatas() { - List MODELS = new ArrayList(); - MultiLineHeadExcelModel model1 = new MultiLineHeadExcelModel(); - model1.setP1("111"); - model1.setP2("222"); - model1.setP3(33); - model1.setP4(44); - model1.setP5("555"); - model1.setP6("666"); - model1.setP7("777"); - model1.setP8("888"); - - MultiLineHeadExcelModel model2 = new MultiLineHeadExcelModel(); - model2.setP1("111"); - model2.setP2("111"); - model2.setP3(11); - model2.setP4(9); - model2.setP5("111"); - model2.setP6("111"); - model2.setP7("111"); - model2.setP8("111"); - - MultiLineHeadExcelModel model3 = new MultiLineHeadExcelModel(); - model3.setP1("111"); - model3.setP2("111"); - model3.setP3(11); - model3.setP4(9); - model3.setP5("111"); - model3.setP6("111"); - model3.setP7("111"); - model3.setP8("111"); - - MODELS.add(model1); - MODELS.add(model2); - MODELS.add(model3); - - return MODELS; - - } - -} diff --git a/src/test/java/function/write/ExcelWriteTest.java b/src/test/java/function/write/ExcelWriteTest.java deleted file mode 100644 index b50f3737..00000000 --- a/src/test/java/function/write/ExcelWriteTest.java +++ /dev/null @@ -1,246 +0,0 @@ -package function.write; - -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.metadata.Font; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.metadata.Table; -import com.alibaba.excel.metadata.TableStyle; -import com.alibaba.excel.support.ExcelTypeEnum; - -import function.model.MultiLineHeadExcelModel; -import function.model.NoAnnModel; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.junit.Test; - -/** - * - * 测试Excel写多个表格 - * @author jipengfei - * @date 2017/05/16 - */ -public class ExcelWriteTest { - - /** - * 一个sheet一张表 - * - * @throws FileNotFoundException - */ - @Test - public void test1() throws FileNotFoundException { - - OutputStream out = new FileOutputStream("/Users/jipengfei/77.xlsx"); - try { - ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,true); - //写第一个sheet, sheet1 数据全是List 无模型映射关系 - Sheet sheet1 = new Sheet(1, 0); - sheet1.setSheetName("第一个sheet"); - writer.write0(getListString(), sheet1); - - //写第二个sheet sheet2 模型上打有表头的注解,合并单元格 - Sheet sheet2 = new Sheet(2, 3, MultiLineHeadExcelModel.class, "第二个sheet", null); - sheet2.setTableStyle(getTableStyle1()); - writer.write(getModeldatas(), sheet2); - - //写sheet3 模型上没有注解,表头数据动态传入 - List> head = new ArrayList>(); - List headCoulumn1 = new ArrayList(); - List headCoulumn2 = new ArrayList(); - List headCoulumn3 = new ArrayList(); - headCoulumn1.add("第一列"); - headCoulumn2.add("第二列"); - headCoulumn3.add("第三列"); - head.add(headCoulumn1); - head.add(headCoulumn2); - head.add(headCoulumn3); - Sheet sheet3 = new Sheet(3, 1, NoAnnModel.class, "第三个sheet", head); - writer.write(getNoAnnModels(), sheet3); - writer.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 一个sheet多张表 - * - * @throws FileNotFoundException - */ - @Test - public void test2() throws FileNotFoundException { - OutputStream out = new FileOutputStream("/Users/jipengfei/77.xlsx"); - try { - ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX,false); - - //写sheet1 数据全是List 无模型映射关系 - Sheet sheet1 = new Sheet(1, 0); - sheet1.setSheetName("第一个sheet"); - Table table1 = new Table(1); - writer.write0(getListString(), sheet1, table1); - writer.write0(getListString(), sheet1, table1); - - //写sheet2 模型上打有表头的注解 - Table table2 = new Table(2); - table2.setTableStyle(getTableStyle1()); - table2.setClazz(MultiLineHeadExcelModel.class); - writer.write(getModeldatas(), sheet1, table2); - - //写sheet3 模型上没有注解,表头数据动态传入,此情况下模型field顺序与excel现实顺序一致 - List> head = new ArrayList>(); - List headCoulumn1 = new ArrayList(); - List headCoulumn2 = new ArrayList(); - List headCoulumn3 = new ArrayList(); - headCoulumn1.add("第一列"); - headCoulumn2.add("第二列"); - headCoulumn3.add("第三列"); - head.add(headCoulumn1); - head.add(headCoulumn2); - head.add(headCoulumn3); - Table table3 = new Table(3); - table3.setHead(head); - table3.setClazz(NoAnnModel.class); - table3.setTableStyle(getTableStyle2()); - writer.write(getNoAnnModels(), sheet1, table3); - writer.write(getNoAnnModels(), sheet1, table3); - - writer.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - out.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private List> getListString() { - List list = new ArrayList(); - list.add("ooo1"); - list.add("ooo2"); - list.add("ooo3"); - list.add("ooo4"); - List list1 = new ArrayList(); - list1.add("ooo1"); - list1.add("ooo2"); - list1.add("ooo3"); - list1.add("ooo4"); - List> ll = new ArrayList>(); - ll.add(list); - ll.add(list1); - return ll; - } - - private List getModeldatas() { - List MODELS = new ArrayList(); - MultiLineHeadExcelModel model1 = new MultiLineHeadExcelModel(); - model1.setP1("111"); - model1.setP2("222"); - model1.setP3(33); - model1.setP4(44); - model1.setP5("555"); - model1.setP6("666"); - model1.setP7("777"); - model1.setP8("888"); - - MultiLineHeadExcelModel model2 = new MultiLineHeadExcelModel(); - model2.setP1("111"); - model2.setP2("111"); - model2.setP3(11); - model2.setP4(9); - model2.setP5("111"); - model2.setP6("111"); - model2.setP7("111"); - model2.setP8("111"); - - MultiLineHeadExcelModel model3 = new MultiLineHeadExcelModel(); - model3.setP1("111"); - model3.setP2("111"); - model3.setP3(11); - model3.setP4(9); - model3.setP5("111"); - model3.setP6("111"); - model3.setP7("111"); - model3.setP8("111"); - - MODELS.add(model1); - MODELS.add(model2); - MODELS.add(model3); - - return MODELS; - - } - - private List getNoAnnModels() { - List MODELS = new ArrayList(); - NoAnnModel model1 = new NoAnnModel(); - model1.setP1("111"); - model1.setP2("111"); - - NoAnnModel model2 = new NoAnnModel(); - model2.setP1("111"); - model2.setP2("111"); - model2.setP3("22"); - - NoAnnModel model3 = new NoAnnModel(); - model3.setP1("111"); - model3.setP2("111"); - model3.setP3("111"); - - MODELS.add(model1); - MODELS.add(model2); - MODELS.add(model3); - - return MODELS; - - } - - private TableStyle getTableStyle1() { - TableStyle tableStyle = new TableStyle(); - Font headFont = new Font(); - headFont.setBold(true); - headFont.setFontHeightInPoints((short)22); - headFont.setFontName("楷体"); - tableStyle.setTableHeadFont(headFont); - tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE); - - Font contentFont = new Font(); - contentFont.setBold(true); - contentFont.setFontHeightInPoints((short)22); - contentFont.setFontName("黑体"); - tableStyle.setTableContentFont(contentFont); - tableStyle.setTableContentBackGroundColor(IndexedColors.GREEN); - return tableStyle; - } - - private TableStyle getTableStyle2() { - TableStyle tableStyle = new TableStyle(); - Font headFont = new Font(); - headFont.setBold(true); - headFont.setFontHeightInPoints((short)22); - headFont.setFontName("宋体"); - tableStyle.setTableHeadFont(headFont); - tableStyle.setTableHeadBackGroundColor(IndexedColors.BLUE); - - Font contentFont = new Font(); - contentFont.setBold(true); - contentFont.setFontHeightInPoints((short)10); - contentFont.setFontName("黑体"); - tableStyle.setTableContentFont(contentFont); - tableStyle.setTableContentBackGroundColor(IndexedColors.RED); - return tableStyle; - } -} diff --git a/src/test/java/function/write/ExcelWriteTest1.java b/src/test/java/function/write/ExcelWriteTest1.java deleted file mode 100644 index 25618e33..00000000 --- a/src/test/java/function/write/ExcelWriteTest1.java +++ /dev/null @@ -1,103 +0,0 @@ -package function.write; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.xssf.streaming.SXSSFSheet; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.junit.Test; - -import java.io.*; -import java.util.ArrayList; -import java.util.List; - -/** - * @author jipengfei - * @date 2017/08/15 - */ -public class ExcelWriteTest1 { - - @Test - public void test(){ - OutputStream out = null; - try { - out = new FileOutputStream("/Users/jipengfei/79.xlsx"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - try { - ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, false); - - //写sheet1 数据全是List 无模型映射关系 - Sheet sheet1 = new Sheet(1, 0); - sheet1.setSheetName("第一个sheet"); - List list = new ArrayList(); - list.add("1");list.add("2");list.add("3"); - List list1 = new ArrayList(); - list1.add("1");list1.add("2");list1.add("3"); - List> lll = new ArrayList>(); - lll.add(list); - writer.write0(lll,sheet1); - writer.write0(lll,sheet1); - writer.finish(); - }catch (Exception e){ - e.printStackTrace(); - } - } - - @Test - public void testWriteAndRead(){ - OutputStream out = null; - try { - out = new FileOutputStream("/Users/jipengfei/79.xlsx"); - } catch (FileNotFoundException e) { - e.printStackTrace(); - } - try { - SXSSFWorkbook wb = new SXSSFWorkbook(10000); - SXSSFSheet sheet = wb.createSheet("11111"); - Row row = sheet.createRow(0); - Cell cell1 = row.createCell(0); - cell1.setCellValue("1111"); - Cell cell2 = row.createCell(1); - cell2.setCellValue("22222"); - Cell cell3 = row.createCell(2); - cell3.setCellValue("33333"); - - - - Row row1 = sheet.createRow(1); - Cell cell21 = row1.createCell(0); - cell21.setCellValue("444"); - Cell cell22 = row1.createCell(1); - cell22.setCellValue("555"); - Cell cell23 = row1.createCell(2); - cell23.setCellValue("666"); - wb.write(out); - out.close(); - - - - - InputStream inputStream = new FileInputStream("/Users/jipengfei/79.xlsx"); - - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - reader.read(new Sheet(1)); - - }catch (Exception e){ - e.printStackTrace(); - } - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/javamodel/ExcelRowJavaModel.java b/src/test/java/javamodel/ExcelRowJavaModel.java deleted file mode 100644 index e3b778cf..00000000 --- a/src/test/java/javamodel/ExcelRowJavaModel.java +++ /dev/null @@ -1,128 +0,0 @@ -package javamodel; - -import java.util.Date; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * Created by jipengfei on 17/3/15. - * - * @author jipengfei - * @date 2017/03/15 - */ -public class ExcelRowJavaModel extends BaseRowModel { - @ExcelProperty(index = 0,value = "银行放款编号") - private int num; - - @ExcelProperty(index = 1,value = "code") - private Long code; - - @ExcelProperty(index = 2,value = "银行存放期期") - private Date endTime; - - @ExcelProperty(index = 3,value = "测试1") - private Double money; - - @ExcelProperty(index = 4,value = "测试2") - private String times; - - @ExcelProperty(index = 5,value = "测试3") - private int activityCode; - - @ExcelProperty(index = 6,value = "测试4") - private Date date; - - @ExcelProperty(index = 7,value = "测试5") - private Double lx; - - @ExcelProperty(index = 8,value = "测试6") - private String name; - - public int getNum() { - return num; - } - - public void setNum(int num) { - this.num = num; - } - - public Long getCode() { - return code; - } - - public void setCode(Long code) { - this.code = code; - } - - public Date getEndTime() { - return endTime; - } - - public void setEndTime(Date endTime) { - this.endTime = endTime; - } - - public Double getMoney() { - return money; - } - - public void setMoney(Double money) { - this.money = money; - } - - public String getTimes() { - return times; - } - - public void setTimes(String times) { - this.times = times; - } - - public int getActivityCode() { - return activityCode; - } - - public void setActivityCode(int activityCode) { - this.activityCode = activityCode; - } - - public Date getDate() { - return date; - } - - public void setDate(Date date) { - this.date = date; - } - - public Double getLx() { - return lx; - } - - public void setLx(Double lx) { - this.lx = lx; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - return "ExcelRowJavaModel{" + - "num=" + num + - ", code=" + code + - ", endTime=" + endTime + - ", money=" + money + - ", times='" + times + '\'' + - ", activityCode=" + activityCode + - ", date=" + date + - ", lx=" + lx + - ", name='" + name + '\'' + - '}'; - } -} diff --git a/src/test/java/javamodel/ExcelRowJavaModel1.java b/src/test/java/javamodel/ExcelRowJavaModel1.java deleted file mode 100644 index 0ca6bac8..00000000 --- a/src/test/java/javamodel/ExcelRowJavaModel1.java +++ /dev/null @@ -1,45 +0,0 @@ -package javamodel; - -import java.util.Date; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -/** - * Created by jipengfei on 17/3/15. - * - * @author jipengfei - * @date 2017/03/15 - */ -public class ExcelRowJavaModel1 extends BaseRowModel { - - @ExcelProperty(index = 0,value = "银行放款编号") - private String num; - - @ExcelProperty(index = 1,value = "code") - private String code; - - public String getNum() { - return num; - } - - public void setNum(String num) { - this.num = num; - } - - public String getCode() { - return code; - } - - public void setCode(String code) { - this.code = code; - } - - @Override - public String toString() { - return "ExcelRowJavaModel1{" + - "num='" + num + '\'' + - ", code='" + code + '\'' + - '}'; - } -} diff --git a/src/test/java/javamodel/IdentificationExcel.java b/src/test/java/javamodel/IdentificationExcel.java deleted file mode 100755 index 7abfbd74..00000000 --- a/src/test/java/javamodel/IdentificationExcel.java +++ /dev/null @@ -1,48 +0,0 @@ -package javamodel; - -import com.alibaba.excel.annotation.ExcelProperty; -import com.alibaba.excel.metadata.BaseRowModel; - -public class IdentificationExcel extends BaseRowModel{ - @ExcelProperty(index=0) - private String materialnumber; - - @ExcelProperty(index=17) - private String unit; - - @ExcelProperty(index=42) - private String specproc; - - public String getMaterialnumber() { - return materialnumber; - } - - public void setMaterialnumber(String materialnumber) { - this.materialnumber = materialnumber; - } - - public String getUnit() { - return unit; - } - - public void setUnit(String unit) { - this.unit = unit; - } - - public String getSpecproc() { - return specproc; - } - - public void setSpecproc(String specproc) { - this.specproc = specproc; - } - - @Override - public String toString() { - return "IdentificationExcel{" + - "materialnumber='" + materialnumber + '\'' + - ", unit='" + unit + '\'' + - ", specproc='" + specproc + '\'' + - '}'; - } -} diff --git a/src/test/java/read/v03/XLS2003FunctionTest.java b/src/test/java/read/v03/XLS2003FunctionTest.java deleted file mode 100644 index a94de404..00000000 --- a/src/test/java/read/v03/XLS2003FunctionTest.java +++ /dev/null @@ -1,87 +0,0 @@ -package read.v03; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import function.listener.ExcelListener; -import function.model.LoanInfo; -import junit.framework.TestCase; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; - -/** - * Created by jipengfei on 17/2/19. - */ -public class XLS2003FunctionTest extends TestCase { - - @Test - public void testExcel2003NoModel() { - InputStream inputStream = getInputStream("2003.xls"); - try { - // 解析每行结果在listener中处理 - ExcelListener listener = new ExcelListener(); - - ExcelReader excelReader = new ExcelReader(inputStream, null, listener); - excelReader.read(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void testExcel2003WithSheet() { - InputStream inputStream = getInputStream("loan1.xls"); - try { - // 解析每行结果在listener中处理 - ExcelListener listener = new ExcelListener(); - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener); - reader.read(new Sheet(1, 1)); - - System.out.println(listener.getDatas()); - } catch (Exception e) { -e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void testExcel2003WithReflectModel() { - InputStream inputStream = getInputStream("loan1.xls"); - try { - // 解析每行结果在listener中处理 - AnalysisEventListener listener = new ExcelListener(); - - ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLS, null, listener); - - excelReader.read(new Sheet(1, 2, LoanInfo.class)); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/read/v07/Read2007MeanWhileWrite.java b/src/test/java/read/v07/Read2007MeanWhileWrite.java deleted file mode 100644 index 15285b0c..00000000 --- a/src/test/java/read/v07/Read2007MeanWhileWrite.java +++ /dev/null @@ -1,91 +0,0 @@ -package read.v07; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import javamodel.ExcelRowJavaModel; -import javamodel.ExcelRowJavaModel1; -import org.junit.Test; -import read.v07.listener.Excel2007NoJavaModelAnalysisListener; -import read.v07.listener.Excel2007WithJavaModelAnalysisListener; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.List; - -/** - * @author jipengfei - * @date 2017/08/27 - */ -public class Read2007MeanWhileWrite { - - @Test - public void noModel() { - - InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx"); - try { - Excel2007NoJavaModelAnalysisListener listener = new Excel2007NoJavaModelAnalysisListener(); - ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/77.xlsx"), - ExcelTypeEnum.XLSX, false); - listener.setExcelWriter(excelWriter); - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet : sheets) { - sheet.setHeadLineMun(1); - reader.read(sheet); - } - excelWriter.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void withModel() { - - InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx"); - try { - Excel2007WithJavaModelAnalysisListener listener = new Excel2007WithJavaModelAnalysisListener(); - ExcelWriter excelWriter = new ExcelWriter(new FileOutputStream("/Users/jipengfei/78.xlsx"), - ExcelTypeEnum.XLSX, true); - listener.setExcelWriter(excelWriter); - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener); - List sheets = reader.getSheets(); - for (Sheet sheet : sheets) { - sheet.setHeadLineMun(1); - if (sheet.getSheetNo() == 1) { - sheet.setHeadLineMun(2); - sheet.setClazz(ExcelRowJavaModel.class); - } - if (sheet.getSheetNo() == 2) { - sheet.setHeadLineMun(1); - sheet.setClazz(ExcelRowJavaModel1.class); - } - reader.read(sheet); - } - excelWriter.finish(); - } catch (Exception e) { - e.printStackTrace(); - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } -} diff --git a/src/test/java/read/v07/Read2007Xlsx.java b/src/test/java/read/v07/Read2007Xlsx.java deleted file mode 100644 index f2e39c34..00000000 --- a/src/test/java/read/v07/Read2007Xlsx.java +++ /dev/null @@ -1,398 +0,0 @@ -package read.v07; - -import com.alibaba.excel.ExcelReader; -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.Sheet; -import com.alibaba.excel.support.ExcelTypeEnum; -import javamodel.ExcelRowJavaModel; -import javamodel.ExcelRowJavaModel1; -import javamodel.IdentificationExcel; -import org.junit.Test; - -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.List; - -/** - * @author jipengfei - * @date 2017/08/27 - */ -public class Read2007Xlsx { - //创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List的方式通知监听者 - @Test - public void noModel() { - InputStream inputStream = getInputStream("2007.xlsx"); - - final List> ll = new ArrayList>(); - try { - ExcelReader reader = new ExcelReader(inputStream, null, - new AnalysisEventListener>() { - @Override - public void invoke(List object, AnalysisContext context) { - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + object); - - ll.add(object); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - reader.read(); - - String aa= ""; - int i= 0; - for (List strings:ll) { - i++; - aa = aa+","+ strings.get(1)+""; - if(i==25000){ - System.out.println(aa); - aa=""; - i=0; - } - - } - System.out.println(aa); - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void withJavaModel() { - InputStream inputStream = getInputStream("2-拆分标识数据库.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener() { - @Override - public void invoke(IdentificationExcel object, AnalysisContext context) { - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + object); - - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - reader.read(new Sheet(1, 1, IdentificationExcel.class)); - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - //创建没有自定义模型,没有sheet的解析器,默认解析所有sheet解析结果以List的方式通知监听者 - @Test - public void noModelMultipleSheet() { - InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener>() { - @Override - public void invoke(List object, AnalysisContext context) { - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + object); - - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - reader.read(); - //reader.finish(); - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - @Test - public void withModelMultipleSheet() { - InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener() { - @Override - public void invoke(Object object, AnalysisContext context) { - ExcelRowJavaModel obj = null; - if (context.getCurrentSheet().getSheetNo() == 1) { - obj = (ExcelRowJavaModel)object; - } - if (context.getCurrentSheet().getSheetNo() == 2) { - obj = (ExcelRowJavaModel)object; - } - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + obj); - - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - - } - }); - - reader.read(new Sheet(1, 2, ExcelRowJavaModel.class)); - reader.read(new Sheet(2, 1, ExcelRowJavaModel1.class)); - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - - @Test - public void withModelMultipleSheet1() { - InputStream inputStream = getInputStream("sss.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener() { - @Override - public void invoke(Object object, AnalysisContext context) { - ExcelRowJavaModel1 obj = null; - if (context.getCurrentSheet().getSheetNo() == 1) { - obj = (ExcelRowJavaModel1)object; - } - //if (context.getCurrentSheet().getSheetNo() == 2) { - // obj = (ExcelRowJavaModel)object; - //} - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + obj); - - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - - } - }); - - reader.read(new Sheet(1, 1, ExcelRowJavaModel1.class)); - // reader.read(new Sheet(2, 1, ExcelRowJavaModel1.class)); - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - //读取shets - @Test - public void getSheets() { - InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener>() { - @Override - public void invoke(List object, AnalysisContext context) { - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - List sheets = reader.getSheets(); - System.out.println(sheets); - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - //获取sheet后再单独一个sheet解析 - @Test - public void getSheetsAndAnalysisNoModel() { - InputStream inputStream = getInputStream("2007NoModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener>() { - @Override - public void invoke(List object, AnalysisContext context) { - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + object); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet : sheets) { - reader.read(sheet); - } - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 获取所有sheet后遍历解析,解析结果含有java模型 - */ - @Test - public void getSheetsAndAnalysisWithModel() { - InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener() { - @Override - public void invoke(Object object, AnalysisContext context) { - ExcelRowJavaModel obj = null; - if (context.getCurrentSheet().getSheetNo() == 1) { - obj = (ExcelRowJavaModel)object; - } - if (context.getCurrentSheet().getSheetNo() == 2) { - obj = (ExcelRowJavaModel)object; - } - System.out.println( - "当前sheet:" + context.getCurrentSheet().getSheetNo() + " 当前行:" + context.getCurrentRowNum() - + " data:" + obj); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet : sheets) { - if (sheet.getSheetNo() == 1) { - sheet.setHeadLineMun(2); - sheet.setClazz(ExcelRowJavaModel.class); - } - if (sheet.getSheetNo() == 2) { - sheet.setHeadLineMun(1); - sheet.setClazz(ExcelRowJavaModel1.class); - } - reader.read(sheet); - } - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - - /** - * 解析过程中断,不再解析(比如解析到某一行出错了,后面不需要再解析了) - */ - @Test - public void interrupt() { - InputStream inputStream = getInputStream("2007WithModelMultipleSheet.xlsx"); - try { - ExcelReader reader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, - new AnalysisEventListener() { - @Override - public void invoke(Object object, AnalysisContext context) { - context.interrupt(); - } - - @Override - public void doAfterAllAnalysed(AnalysisContext context) { - } - }); - - List sheets = reader.getSheets(); - System.out.println(sheets); - for (Sheet sheet : sheets) { - if (sheet.getSheetNo() == 1) { - sheet.setHeadLineMun(2); - sheet.setClazz(ExcelRowJavaModel.class); - } - if (sheet.getSheetNo() == 2) { - sheet.setHeadLineMun(1); - sheet.setClazz(ExcelRowJavaModel1.class); - } - reader.read(sheet); - } - - } catch (Exception e) { - e.printStackTrace(); - - } finally { - try { - inputStream.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - private InputStream getInputStream(String fileName) { - return Thread.currentThread().getContextClassLoader().getResourceAsStream("" + fileName); - - } - - - - -} diff --git a/src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java b/src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java deleted file mode 100644 index 85b6e766..00000000 --- a/src/test/java/read/v07/listener/Excel2007NoJavaModelAnalysisListener.java +++ /dev/null @@ -1,37 +0,0 @@ -package read.v07.listener; - -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author jipengfei - * @date 2017/08/27 - */ -public class Excel2007NoJavaModelAnalysisListener extends AnalysisEventListener { - - private ExcelWriter excelWriter; - - public ExcelWriter getExcelWriter() { - return excelWriter; - } - - public void setExcelWriter(ExcelWriter excelWriter) { - this.excelWriter = excelWriter; - } - - public void invoke(Object object, AnalysisContext context) { - List> ll = new ArrayList>(); - ll.add((List)object); - System.out.println(object); - excelWriter.write0(ll, context.getCurrentSheet()); - } - - public void doAfterAllAnalysed(AnalysisContext context) { - - } - -} diff --git a/src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java b/src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java deleted file mode 100644 index e52bcdfd..00000000 --- a/src/test/java/read/v07/listener/Excel2007WithJavaModelAnalysisListener.java +++ /dev/null @@ -1,40 +0,0 @@ -package read.v07.listener; - -import com.alibaba.excel.ExcelWriter; -import com.alibaba.excel.context.AnalysisContext; -import com.alibaba.excel.event.AnalysisEventListener; -import com.alibaba.excel.metadata.BaseRowModel; -import com.alibaba.excel.metadata.Sheet; -import javamodel.ExcelRowJavaModel; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author jipengfei - */ -public class Excel2007WithJavaModelAnalysisListener extends AnalysisEventListener { - - private ExcelWriter excelWriter; - - public ExcelWriter getExcelWriter() { - return excelWriter; - } - - public void setExcelWriter(ExcelWriter excelWriter) { - this.excelWriter = excelWriter; - } - - public void invoke(Object object, AnalysisContext context) { - List< BaseRowModel> ll = new ArrayList(); - ll.add((BaseRowModel)object); - Sheet sheet = context.getCurrentSheet(); - sheet.setClazz(ExcelRowJavaModel.class); - excelWriter.write(ll,sheet); - } - - public void doAfterAllAnalysed(AnalysisContext context) { - - } - -} diff --git a/src/test/resources/111.xlsx b/src/test/resources/111.xlsx deleted file mode 100644 index b5efcd91..00000000 Binary files a/src/test/resources/111.xlsx and /dev/null differ diff --git a/src/test/resources/1111.xlsx b/src/test/resources/1111.xlsx deleted file mode 100644 index a062def1..00000000 Binary files a/src/test/resources/1111.xlsx and /dev/null differ diff --git a/src/test/resources/2003.xls b/src/test/resources/2003.xls index cef6344c..3c2fa34d 100644 Binary files a/src/test/resources/2003.xls and b/src/test/resources/2003.xls differ diff --git a/src/test/resources/2007.xlsx b/src/test/resources/2007.xlsx index fe19ea0f..73eb67b4 100644 Binary files a/src/test/resources/2007.xlsx and b/src/test/resources/2007.xlsx differ diff --git a/src/test/resources/2007NoModelBigFile.xlsx b/src/test/resources/2007NoModelBigFile.xlsx deleted file mode 100644 index 5d5a5c17..00000000 Binary files a/src/test/resources/2007NoModelBigFile.xlsx and /dev/null differ diff --git a/src/test/resources/2007NoModelMultipleSheet.xlsx b/src/test/resources/2007NoModelMultipleSheet.xlsx deleted file mode 100644 index 45a2a742..00000000 Binary files a/src/test/resources/2007NoModelMultipleSheet.xlsx and /dev/null differ diff --git a/src/test/resources/2007WithModel.xlsx b/src/test/resources/2007WithModel.xlsx deleted file mode 100644 index 73ab8065..00000000 Binary files a/src/test/resources/2007WithModel.xlsx and /dev/null differ diff --git a/src/test/resources/2007WithModelMultipleSheet.xlsx b/src/test/resources/2007WithModelMultipleSheet.xlsx deleted file mode 100644 index 0c601093..00000000 Binary files a/src/test/resources/2007WithModelMultipleSheet.xlsx and /dev/null differ diff --git a/src/test/resources/2007_1.xlsx b/src/test/resources/2007_1.xlsx deleted file mode 100644 index b782ca0d..00000000 Binary files a/src/test/resources/2007_1.xlsx and /dev/null differ diff --git a/src/test/resources/77.xlsx b/src/test/resources/77.xlsx deleted file mode 100644 index 800caccb..00000000 Binary files a/src/test/resources/77.xlsx and /dev/null differ diff --git a/src/test/resources/sss.xlsx b/src/test/resources/sss.xlsx deleted file mode 100644 index e3088519..00000000 Binary files a/src/test/resources/sss.xlsx and /dev/null differ diff --git a/src/test/resources/temp.xlsx b/src/test/resources/temp.xlsx new file mode 100644 index 00000000..2149a237 Binary files /dev/null and b/src/test/resources/temp.xlsx differ