아파 치 POI 3.9 해석 엑셀

16255 단어 Java
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Font;
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.usermodel.WorkbookFactory;
import org.apache.struts2.ServletActionContext;

import com.sf.framework.server.core.context.UserContext;
import com.sf.module.tcascommon.cfg.SysConfigProperties;

/**
 *   Apache POI3.9 Excel       
 * @param           
 * @author zhangzikui
 */
public class ExcelParser
{
	private static final String EMPTY_STRING = "";
	
	private Class entityClass = null;
	private Workbook workBook = null;
	private CellStyle errorCellStyle = null;
	private final List columnMapperList = new ArrayList();
	private final Map errorMessage = new HashMap();
	
	private int startRowIndex = 1;
	private int promptColumnIndex = 1;
	
	private int lastRowNum = 0;
	private int successCount = 0;
	private int errorCount = 0;
	
	/**
	 *     
	 * @param excelFile Excel    
	 * @param clazz          
	 * @throws InvalidFormatException
	 * @throws IOException
	 */
	public ExcelParser(File excelFile, Class clazz, int startRowIndex, int promptColumnIndex) throws InvalidFormatException, IOException {
		this.entityClass = clazz;
		this.startRowIndex = startRowIndex;
		this.promptColumnIndex = promptColumnIndex;
		this.createWorkbook(excelFile);
	}
	
	/**
	 *   poi workbook  
	 * @param excelFile
	 * @throws InvalidFormatException
	 * @throws IOException
	 */
	private void createWorkbook(File excelFile) throws InvalidFormatException, IOException
	{
		FileInputStream fis = null;

		try
		{
			fis = new FileInputStream(excelFile);
			this.workBook = WorkbookFactory.create(fis);
		}
		finally
		{
			if(fis != null)
			{
				try
				{
					fis.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		if(this.workBook != null)
		{
			Sheet firstSheet = this.workBook.getSheetAt(0);
			
			if(firstSheet != null)
			{
				this.lastRowNum = firstSheet.getLastRowNum();
			}
			
			//          、  、  
			Font font = this.workBook.createFont();
			font.setColor(Font.COLOR_RED);
			this.errorCellStyle = this.workBook.createCellStyle();
			this.errorCellStyle.setFont(font);
		}
	}
	
	/**
	 *   Excel  ,      List   
	 * @param startRowIndex         , 0  
	 * @return         
	 * @throws NoSuchFieldException
	 */
	public List parseExcel() throws NoSuchFieldException
	{
		List resultList = new ArrayList();
		
		if(this.columnMapperList == null || this.columnMapperList.size() < 1 || this.startRowIndex < 0)
		{
			return resultList;
		}
		
		if(this.workBook != null)
		{
			Sheet firstSheet = this.workBook.getSheetAt(0);
			
			if(firstSheet != null)
			{
				Row titleRow = firstSheet.getRow(this.startRowIndex - 1);
				for(ColumnMapper mapper : this.columnMapperList)
				{
					mapper.setField(getFieldByName(this.entityClass, mapper.getFieldName()));
					
					//       
					if(titleRow != null && titleRow.getCell(mapper.getColumnIndex()) != null)
					{
						mapper.setColumnTitle(titleRow.getCell(mapper.getColumnIndex()).getStringCellValue().trim());
					}
				}
				
				Cell cell = null;
				Row row = null;
				Object fieldValue = null;
				T entityObject = null;
				
				for(int rowIndex = this.startRowIndex; rowIndex <= this.lastRowNum; rowIndex++)
				{
					row = firstSheet.getRow(rowIndex);
					if(row != null)
					{
						try
						{
							entityObject = this.entityClass.newInstance();
						}
						catch(Exception e1)
						{
							e1.printStackTrace();
							break;
						}
						
						boolean hasError = false;
						for(ColumnMapper mapper : this.columnMapperList)
						{
							cell = row.getCell(mapper.getColumnIndex());
							
							if(mapper.getValidator() != null)
							{
								try
								{
									mapper.getValidator().validate(cell);
								}
								catch(Exception e1)
								{
									hasError = true;
									this.errorMessage.put(rowIndex, mapper.getColumnTitle() + "[ " + (mapper.getColumnIndex()+1) + " ]:" + e1.getMessage());
									++this.errorCount;
									break;
								}
							}
							
							try
							{
								fieldValue = changeCellToObject(cell, mapper);
							}
							catch(Exception e)
							{
								hasError = true;
								this.errorMessage.put(rowIndex, mapper.getColumnTitle() + "[ " + (mapper.getColumnIndex()+1) + " ]:" + e.getMessage());
								++this.errorCount;
								break;
							}
							
							try
							{
								mapper.getField().set(entityObject, fieldValue);
							}
							catch(Exception e)
							{
								hasError = true;
								this.errorMessage.put(rowIndex, mapper.getColumnTitle() + "[ " + (mapper.getColumnIndex()+1) + " ]:" + e.getMessage());
								++this.errorCount;
								break;
							}
						}
						
						if(!hasError)
						{
							resultList.add(entityObject);
							++this.successCount;
						}
					}
				}
			}
		}
		
		return resultList;
	}
	
	/**
	 *         ,         
	 * @param rowNum     , 0  
	 * @param columnNum     , 0  
	 * @return Cell      
	 */
    public Cell getCellByIndex(int rowNum, int columnNum)
    {
    	if(this.workBook != null)
		{
			Sheet firstSheet = this.workBook.getSheetAt(0);
			
			if(firstSheet != null && firstSheet.getRow(rowNum) != null)
			{
				return firstSheet.getRow(rowNum).getCell(columnNum);
			}
		}
    	
    	return null;
    }
    
    /**
     *             
     * @param messageCellIndex Excel         , 1  
     * @return            
     * @throws Exception
     */
    public String getPromptFileName() throws Exception 
    {
    	if(this.promptColumnIndex < 1)
    	{
    		return null;
    	}
    	
    	for(Map.Entry entry : this.errorMessage.entrySet())
    	{
    		addErrorMessage(entry.getKey(), this.promptColumnIndex, entry.getValue());
    	}
    	
    	File file = null;
    	OutputStream os = null;
		try
		{
			file = new File(getTemporaryFilePath(), getTemporaryFileName());
			os = new FileOutputStream(file);
			this.workBook.write(os);
		}
		catch(Exception e)
		{
			throw new Exception("          ", e);
		}
		finally
		{
			if(os != null)
			{
				try
				{
					os.close();
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		}
		
		return file.getName();
    }
    
    /**
     *         
     * @param rowIndex     , 0  
     * @param cellIndex     , 0  
     * @param message     
     */
    private void addErrorMessage(int rowIndex, int cellIndex, String message)
    {
    	if(this.workBook != null)
		{
			Sheet firstSheet = this.workBook.getSheetAt(0);
			
			if(firstSheet != null && firstSheet.getRow(rowIndex) != null)
			{
				Cell msgCell = firstSheet.getRow(rowIndex).createCell(cellIndex, Cell.CELL_TYPE_STRING);
				msgCell.setCellStyle(this.errorCellStyle);
				msgCell.setCellValue(message);
			}
		}
    }
    
    /**
     *        
     * @param mapper
     */
    public void addColumnMapper(ColumnMapper mapper)
    {
    	this.columnMapperList.add(mapper);
    }
    
    /**
     *          
     * @return          
     */
	public int getSuccessCount()
	{
		return successCount;
	}

	/**
     *          
     * @return          
     */
	public int getErrorCount()
	{
		return errorCount;
	}

	/**
	 *   Excel         , 0  
	 * @return        , 0  
	 */
	public int getLastRowNum()
	{
		return lastRowNum;
	}
    
	/**
	 *        Java       
	 * @param cell      
	 * @param mapper     
	 * @return     Java  
	 * @throws Exception
	 */
	private static Object changeCellToObject(Cell cell, ColumnMapper mapper) throws Exception 
	{
		Object fieldValue = null;
		Class> fieldType = mapper.getField().getType();
		String cellValueString = changeCellToString(cell, fieldType);
		
		if(cellValueString != null && !(EMPTY_STRING.equals(cellValueString.trim())))
		{
			try
			{
				if(String.class.equals(fieldType))
				{
					fieldValue = cellValueString;
				}
				else if(Integer.class.equals(fieldType) || int.class.equals(fieldType))
				{
					fieldValue = Integer.valueOf(cellValueString);
				}
				else if(Long.class.equals(fieldType) || long.class.equals(fieldType))
				{
					fieldValue = Long.valueOf(cellValueString);
				}
				else if(Float.class.equals(fieldType) || float.class.equals(fieldType))
				{
					fieldValue = Float.valueOf(cellValueString);
				}
				else if(Double.class.equals(fieldType) || double.class.equals(fieldType))
				{
					fieldValue = Double.valueOf(cellValueString);
				}
				else if(Date.class.equals(fieldType))
				{
					switch(cell.getCellType())
					{
						case Cell.CELL_TYPE_STRING:
						{
							fieldValue = new SimpleDateFormat(mapper.getDateFormatString().trim()).parse(cellValueString);
							break;
						}
						case Cell.CELL_TYPE_NUMERIC:
						{
							if(DateUtil.isCellDateFormatted(cell))
							{
								fieldValue = cell.getDateCellValue();
							}
							break;
						}
					}
				}
			}
			catch(NumberFormatException ne)
			{
				throw new Exception("      ");
			}
			catch(ParseException pe)
			{
				throw new Exception("      ");
			}
			catch(IllegalArgumentException ae)
			{
				throw new Exception("        ");
			}
		}
		
		return fieldValue;
	}
	
	/**
	 *                
	 * @param cell      
	 * @param fieldType Java     
	 * @return           
	 */
	private static String changeCellToString(Cell cell, Class> fieldType)
	{
		String cellValueString = "";
		
		if(cell != null)
		{
			switch(cell.getCellType())
			{
				case Cell.CELL_TYPE_STRING:
				{
					cellValueString = cell.getStringCellValue().trim();
					break;
				}
				
				case Cell.CELL_TYPE_NUMERIC:
				{
					if(DateUtil.isCellDateFormatted(cell))
					{
						cellValueString = EMPTY_STRING;
					}
					else
					{
						if(Float.class.equals(fieldType) || float.class.equals(fieldType)
						  || Double.class.equals(fieldType) || double.class.equals(fieldType))
						{
							cellValueString = String.valueOf(cell.getNumericCellValue());
						}
						else
						{
							cell.setCellType(Cell.CELL_TYPE_STRING);
							cellValueString = cell.getStringCellValue().trim();
						}
					}
					break;
				}
				
				case Cell.CELL_TYPE_BLANK:
				{
					cellValueString = EMPTY_STRING;
					break;
				}
				
				case Cell.CELL_TYPE_FORMULA:
				{
					try
					{
						cellValueString = String.valueOf(cell.getNumericCellValue());
					}
					catch(Exception e)
					{
						cellValueString = cell.getRichStringCellValue().toString().trim();
					}
					break;
				}
				
				default:
				{
					cellValueString = EMPTY_STRING;
				}
			}
		}
		else
		{
			cellValueString = EMPTY_STRING;
		}
		
		return cellValueString;
	}
	
    private static Field getFieldByName(Class> clazz, String fieldName) throws NoSuchFieldException
    {
    	Field field = null;
    	try
		{
			field = clazz.getDeclaredField(fieldName);
		}
		catch(NoSuchFieldException e)
		{
			field = clazz.getSuperclass().getDeclaredField(fieldName);
		}
		
		field.setAccessible(true);
		
		return field;
    }
    
    /**
     *            
     * @return        File  
     * @throws IOException
     */
    private static File getTemporaryFilePath() throws IOException
    {
    	File tempPath =new File((File)(ServletActionContext.getServletContext().getAttribute("javax.servlet.context.tempdir")),
    									SysConfigProperties.EXCEL_CHILD_DIR);
    	
		if(!tempPath.exists())
		{
			tempPath.mkdirs();
		}

		return tempPath.getCanonicalFile();
    }
    
    /**
     *          
     * @return        
     * @throws IOException
     */
    private static String getTemporaryFileName()
	{
		StringBuilder fileName = new StringBuilder(UserContext.getContext()
															  .getCurrentUser()
															  .getUsername());
		
		fileName.append("_")
				.append(UUID.randomUUID().toString());
		
		return fileName.toString();
	}
    
    /**
     * Excel  JAVA        ,
     *          
     */
    public static class ColumnMapper
    {
    	private int columnIndex;
    	private String columnTitle = "";
    	private String fieldName;
    	private String dateFormatString;
    	private Field field;
    	private ColumnValidator validator;
    	
    	/**
    	 *        
    	 * @param columnIndex   Excel       , 0  
    	 * @param fieldName     Java    
    	 * @param dateFormatString     ( “yyyy-MM-dd”),      Java    ,       
    	 * @param validator           
    	 */
    	public ColumnMapper(int columnIndex, String fieldName, String dateFormatString, ColumnValidator validator){
			this.columnIndex = columnIndex;
			this.fieldName = fieldName;
			this.dateFormatString = dateFormatString;
			this.validator = validator;
		}

		public int getColumnIndex()
    	{
    		return columnIndex;
    	}
    	
    	public void setColumnIndex(int columnIndex)
		{
			this.columnIndex = columnIndex;
		}
    	
    	public String getColumnTitle()
		{
			return columnTitle;
		}

    	private void setColumnTitle(String columnTitle)
		{
			this.columnTitle = columnTitle;
		}
    	
    	public String getFieldName()
		{
			return fieldName;
		}
    	
    	public void setFieldName(String fieldName)
		{
			this.fieldName = fieldName;
		}
    	
    	public String getDateFormatString()
		{
			return dateFormatString;
		}

		public void setDateFormatString(String dateFormatString)
		{
			this.dateFormatString = dateFormatString;
		}
		
		private void setField(Field field)
		{
			this.field = field;
		}
		
		private Field getField()
    	{
    		return field;
    	}
    	
    	public ColumnValidator getValidator()
    	{
    		return validator;
    	}
    	
    	public void setValidator(ColumnValidator validator)
		{
			this.validator = validator;
		}
    }
    
    /**
     * Excel        。
     *      ,            
     */
	public interface ColumnValidator
	{
		/**
		 *         。
		 *      ,            
		 * @param cell      
		 * @throws Exception       
		 */
		public void validate(Cell cell) throws Exception;
	}
	
	
	/**
	 *        
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception
	{
		//    Excel    
		File file = new File("E:/Download/DeptPriceTemplate_import.xls");
		
		//     (Object          Java ,    )
		//            ( 0  ),              ( 1  )
		ExcelParser parser = new ExcelParser(file, Object.class, 1, 10);
		
		//  Excel        (      ,     ,      )
		System.out.println("      :" + parser.getLastRowNum());
		
		//       
		ColumnValidator cValidator = new ColumnValidator(){
			public void validate(Cell cell) throws Exception{
				if(cell==null || "".equals(cell.toString().trim()))
				{
					throw new Exception("       !");
				}
			}
		};
		
		//      (   0  )
		parser.addColumnMapper(new ColumnMapper(0, "empCode", null, null));
		parser.addColumnMapper(new ColumnMapper(1, "workDate", "yyyy-MM-DD", null));
		parser.addColumnMapper(new ColumnMapper(2, "workTime", null, cValidator));
		
		//    
		List list = parser.parseExcel();
		
		//           
		System.out.println("    :" + list.size() + "    :" + parser.getErrorCount());
		
		//           
		if(parser.getErrorCount() > 0)
		{
			String errorFilePath = parser.getPromptFileName();
			System.out.println(errorFilePath);
		}
	}
}

좋은 웹페이지 즐겨찾기