xlstransformer.java
来自「一个java生成自动生成Excel」· Java 代码 · 共 595 行 · 第 1/2 页
JAVA
595 行
package net.sf.jxls.transformer;import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.HashMap;import java.util.HashSet;import java.util.List;import java.util.Map;import java.util.Set;import net.sf.jxls.controller.WorkbookTransformationController;import net.sf.jxls.controller.WorkbookTransformationControllerImpl;import net.sf.jxls.exception.ParsePropertyException;import net.sf.jxls.formula.CommonFormulaResolver;import net.sf.jxls.formula.FormulaController;import net.sf.jxls.formula.FormulaResolver;import net.sf.jxls.processor.CellProcessor;import net.sf.jxls.processor.PropertyPreprocessor;import net.sf.jxls.processor.RowProcessor;import net.sf.jxls.util.Util;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.poifs.filesystem.POIFSFileSystem;/** * <p> This class uses excel template to generate excel file filled with required objects and collections. * <p/> * @author Leonid Vysochyn * @author Vincent Dutat */public class XLSTransformer { protected final Log log = LogFactory.getLog(getClass()); /** * property preprocessors will be applied before main transformation starts */ private List propertyPreprocessors = new ArrayList(); private List rowProcessors = new ArrayList(); private List cellProcessors = new ArrayList();// private Map taglibs = new HashMap(); private final String TAGLIB_DEFINITION_FILE = "jxls-core-taglib.xml"; /** * Registers Property Preprocessor that will be applied before main template transformation * it is possible to have many Property Preprocessors * @param propPreprocessor - {@link PropertyPreprocessor} interface implementation */ public void registerPropertyPreprocessor(PropertyPreprocessor propPreprocessor) { if (propPreprocessor != null) { propertyPreprocessors.add(propPreprocessor); } } /** * Registers {@link net.sf.jxls.processor.RowProcessor} object * @param rowProcessor {@link net.sf.jxls.processor.RowProcessor} to register */ public void registerRowProcessor(RowProcessor rowProcessor) { if (rowProcessor != null) { rowProcessors.add(rowProcessor); } } /** * Registers {@link net.sf.jxls.processor.CellProcessor} object * @param cellProcessor {@link net.sf.jxls.processor.CellProcessor to register} */ public void registerCellProcessor(CellProcessor cellProcessor) { if (cellProcessor != null) { cellProcessors.add(cellProcessor); } } /** * Mark a collection as static collection. * All static collection rows are presented in Excel template and will not be expanded * @param collectionName - Collection name to mark as fixed size collection */ public void markAsFixedSizeCollection(String collectionName) { fixedSizeCollections.add(collectionName); }// public void registerTaglib(String prefix, Taglib taglib){// if( taglibs.containsKey( prefix ) ){// throw new TaglibRegistrationException( "Tag library with prefix '" + prefix + "' already registered");// }else{// taglibs.put( prefix, taglib );// }// } /** * Column numbers to hide */ private short[] columnsToHide; private Set spreadsheetsToRemove = new HashSet(); private Map spreadsheetsToRename = new HashMap(); // hash map 'spdsheet tpl name' => 'new name' private String[] columnPropertyNamesToHide; Map customTags = new HashMap(); /** * Stores the names of all 'fixed size' collections. * 'Fixed size' collection is a collection with fixed number of items which do not require to create new rows in excel file * because all rows for them are already presented in template file. */ private Set fixedSizeCollections = new HashSet(); /** * {@link Set} of all collections to outline */ private Set groupedCollections = new HashSet(); /** * {@link net.sf.jxls.transformer.Configuration} class */ private Configuration configuration; public Configuration getConfiguration() { return configuration; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public XLSTransformer() { this(new Configuration()); } public XLSTransformer(Configuration configuration) { if( configuration!=null ){ this.configuration = configuration; }else{ this.configuration = new Configuration(); } //todo// registerTaglib( TAGLIB_DEFINITION_FILE ); }// public void registerTaglib(String taglibFileName){// TaglibXMLParser parser = new TaglibXMLParser();// Taglib taglib = parser.parseTaglibXMLFile( taglibFileName );// } private WorkbookTransformationController workbookTransformationController; private FormulaResolver formulaResolver; /** * @return {@link net.sf.jxls.formula.FormulaResolver} used to resolve coded formulas */ public FormulaResolver getFormulaResolver() { return formulaResolver; } /** * Sets {@link FormulaResolver} to be used in resolving formula * @param formulaResolver {@link FormulaResolver} implementation to set */ public void setFormulaResolver(FormulaResolver formulaResolver) { this.formulaResolver = formulaResolver; } public boolean isJexlInnerCollectionsAccess() { return configuration.isJexlInnerCollectionsAccess(); } public void setJexlInnerCollectionsAccess(boolean jexlInnerCollectionsAccess) { configuration.setJexlInnerCollectionsAccess( jexlInnerCollectionsAccess ); } /** * Set this collection to be grouped (outlined). * @param collectionName - Collection name to use for grouping */ public void groupCollection(String collectionName) { groupedCollections.add(collectionName); } /** * Creates new .xls file at a given path using specified excel template file and a number of beans. * This method invokes {@link #transformXLS(InputStream is, Map beanParams)} passing input stream from a template file * and then writing resulted HSSFWorkbook into required output file. * * @param srcFilePath Path to source .xls template file * @param beanParams Map of beans to be applied to .xls template file with keys corresponding to bean aliases in template * @param destFilePath Path to result .xls file * @throws ParsePropertyException if there were any problems in evaluating specified property value from a bean * @throws IOException if there were any access or input/output problems with source or destination file */ public void transformXLS(String srcFilePath, Map beanParams, String destFilePath) throws ParsePropertyException, IOException { InputStream is = new BufferedInputStream(new FileInputStream(srcFilePath)); HSSFWorkbook workbook = transformXLS(is, beanParams); OutputStream os = new BufferedOutputStream(new FileOutputStream(destFilePath)); workbook.write(os); is.close(); os.flush(); os.close(); } /** * Creates HSSFWorkbook instance based on .xls template from a given InputStream and a number of beans * * @param is xls InputStream with required * @param beanParams Beans in a map under keys used in .xls template to access to the beans * @return new {@link HSSFWorkbook} generated by inserting beans into corresponding excel template * @throws net.sf.jxls.exception.ParsePropertyException if there were any problems in evaluating specified property value from a bean */ public HSSFWorkbook transformXLS(InputStream is, Map beanParams) throws ParsePropertyException { HSSFWorkbook hssfWorkbook = null; try { POIFSFileSystem fs = new POIFSFileSystem(is); hssfWorkbook = new HSSFWorkbook(fs); transformWorkbook(hssfWorkbook, beanParams); } catch (IOException e) { e.printStackTrace(); } return hssfWorkbook; } public void transformWorkbook(HSSFWorkbook hssfWorkbook, Map beanParams) { Workbook workbook = createWorkbook( hssfWorkbook ); exposePOIObjects(workbook, beanParams); workbookTransformationController = new WorkbookTransformationControllerImpl( workbook ); preprocess(hssfWorkbook); SheetTransformer sheetTransformer = new SheetTransformer( fixedSizeCollections, groupedCollections, rowProcessors, cellProcessors, configuration) ; for (int sheetNo = 0; sheetNo < hssfWorkbook.getNumberOfSheets(); sheetNo++) { final String spreadsheetName = hssfWorkbook.getSheetName(sheetNo); if( spreadsheetName != null && !spreadsheetName.startsWith( configuration.getExcludeSheetProcessingMark() )){ if (!isSpreadsheetToRemove(spreadsheetName)) { if (isSpreadsheetToRename(spreadsheetName)) { hssfWorkbook.setSheetName(sheetNo, getSpreadsheetToReName(spreadsheetName)); } Sheet sheet = workbook.getSheetAt( sheetNo ); sheetTransformer.transformSheet( workbookTransformationController, sheet, beanParams ); } else { // let's remove spreadsheet workbook.removeSheetAt( sheetNo ); sheetNo--; } } } updateFormulas(); } private void exposePOIObjects(Workbook workbook, Map beanParams) { beanParams.put( configuration.getWorkbookKeyName(), workbook.getHssfWorkbook() ); } /** * This method transforms given XLS input stream template into multiple sheets workbook * creating separate Excel worksheet for every object in the list * @param is - {@link InputStream} for source XLS template file * @param objects - List of beans where each list item should be exported into a separated worksheet * @param newSheetNames - Sheet names to be used for newly created worksheets * @param beanName - Bean name to be used for a list item when processing sheet * @param beanParams - Common bean map containing all other objects to be used in the workbook * @param startSheetNum - Worksheet number (zero based) of the worksheet that needs to be used to create multiple worksheets * @return new {@link HSSFWorkbook} object containing the result of transformation * @throws net.sf.jxls.exception.ParsePropertyException - {@link ParsePropertyException} is thrown when some property can't be parsed */ public HSSFWorkbook transformMultipleSheetsList(InputStream is, List objects, List newSheetNames, String beanName, Map beanParams, int startSheetNum) throws ParsePropertyException { HSSFWorkbook hssfWorkbook = null; try { if( beanParams!=null && beanParams.containsKey( beanName )){ throw new IllegalArgumentException("Selected bean name '" + beanName + "' already exists in the bean map"); } if( beanName==null ){ throw new IllegalArgumentException(("Bean name must not be null" ) ); } if( beanParams == null ){ beanParams = new HashMap(); } POIFSFileSystem fs = new POIFSFileSystem(is); hssfWorkbook = new HSSFWorkbook(fs);// preprocess(hssfWorkbook);//
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?