poi 操作excel之導入excel

用了好久的 poi 今天總結下

/**
 * @description 讀取並解析excel
 */
public class ImportExcel {

	/**
	 * 對外提供讀取excel 的方法
	 * @param file
	 * @return
	 * @throws IOException
	 */
	public static List<List<Object>> readExcel(String fileUrl,int index) throws IOException{
		String extension = fileUrl.lastIndexOf(".") == -1 ? "" : fileUrl
				.substring(fileUrl.lastIndexOf(".") + 1);
		if("xls".equals(extension)){
			return read2003Excel(fileUrl,index);//原模板導入
		} else if("xlsx".equals(extension)){
			return read2007Excel(fileUrl,index);
		} else {
			throw new IOException("不支持文件類型");
		}

	}

	/**
	 * 讀取 office 2003 Excel文件    
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private static List<List<Object>> read2003Excel(String file,int index) throws IOException {
		List<List<Object>> list = new LinkedList<List<Object>>();
		HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
		HSSFSheet sheet = hwb.getSheetAt(index);
//		String sheetName = sheet.getSheetName();0
		
		
		Object value = null;
		HSSFRow row = null;
		HSSFCell cell = null;
		int counter = 0;
		// 獲取第一個實際行的下標  行數-1
		int firstRow = sheet.getFirstRowNum();
		//getPhysicalNumberOfRows  獲取有記錄的行數,即:最後有數據的行是第n行,前面有m行是空行沒數據,則返回n-m;
		int rows = sheet.getPhysicalNumberOfRows();
		
		for(int i = firstRow;counter <rows;i++){
			row = sheet.getRow(i);
			if(null == row){
				continue;
			}else {
				counter++;
			}
			List<Object> linked = new LinkedList<Object>();
			
			// 獲取在某行第一個單元格的下標
			int firstIndex = row.getFirstCellNum();
			// 獲取在某行的列數
			int atRow = row.getLastCellNum()-1;
			for (int j = firstIndex; j <= atRow;j++) {
				cell = row.getCell(j);
				if(null == cell){
					continue;
				}
				DecimalFormat df = new DecimalFormat("0"); //格式化 number String 字符
				//格式化日期字符串
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				DecimalFormat nf = new DecimalFormat("0.00"); //格式化數字
			
				Boolean isInteger = cell.toString().matches("^[-\\+]?[\\d]*$");
				switch (cell.getCellType()){
				case XSSFCell.CELL_TYPE_STRING:
//					System.out.println(i + "行" + j + "列 is String Type");
					value = cell.getStringCellValue();
					break;
				case XSSFCell.CELL_TYPE_NUMERIC:
//					System.out.println(i + "行" + j + "列 is Number type ; DateFormat:");
					Object a = cell.getCellStyle().getDataFormatString();
					if("0".equals(cell.getCellStyle().getDataFormatString())){
						value = df.format(cell.getNumericCellValue()); 
					}else if("General".equals(cell.getCellStyle().getDataFormatString())){
						Double mainWastage = Double.parseDouble(cell.toString());
						if(mainWastage.intValue()-mainWastage==0){//判斷是否符合取整條件
							value = df.format(cell.getNumericCellValue());
						}else{
							value = nf.format(cell.getNumericCellValue());
						}
						
					} else {
						value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
					}
					break;
				case XSSFCell.CELL_TYPE_BOOLEAN:
//					System.out.println(i + "行" + j + "列 is boolean type");
					value = cell.getBooleanCellValue();
					break;
				case XSSFCell.CELL_TYPE_BLANK:	
//					System.out.println(i + "行" + j + "列 is Blank type");
					value = " ";
					break;
				case XSSFCell.CELL_TYPE_FORMULA:
		            
		            try {
		               value = String.valueOf(cell.getNumericCellValue());
		            	 } 
		            catch (IllegalStateException e) {
		            	value = String.valueOf(cell.getRichStringCellValue());
		                }
		           
		            break;	
				default :
//					System.out.println(i + "行" + j + "列 is default type");
					value = cell.toString();
				}
				if(null == value || "".equals(value)){
					continue;
				}
				linked.add(value);
			}
			list.add(linked);
		}
		return list;
	}
	
	/**
	 * 讀取 office 2007 Excel文件
	 * @param file
	 * @return
	 * @throws IOException
	 */
	private static List<List<Object>> read2007Excel(String file,int index) throws IOException {
		List<List<Object>> list = new LinkedList<List<Object>>(); 
		// 構造 XSSFWorkbook 對象, strPath 傳入文件路徑
		XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file)); 
		// 讀取第一章表格內容
		XSSFSheet sheet = xwb.getSheetAt(index);
		Object value = null;
		XSSFRow row = null;   //行
		XSSFCell cell = null;  //列
		int counter = 0;
		
		for (int i = sheet.getFirstRowNum(); counter < sheet.getPhysicalNumberOfRows(); i++) {
			row = sheet.getRow(i);
			if(null == row){
				continue;
			} else {
				counter++;
			}
			List<Object> linked = new LinkedList<Object>();
			for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
				cell = row.getCell(j);
				if(null == cell){
					continue;
				}
				//格式化  number String 字符
				DecimalFormat df = new DecimalFormat("0");
				//格式化日期字符串
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				//格式化數字
				DecimalFormat nf = new DecimalFormat("0.00");
				switch (cell.getCellType()) {
				case XSSFCell.CELL_TYPE_STRING:
					value = cell.getStringCellValue(); 
//					System.out.println(i + "行" + j + "列  is :" + value);
					break;
				case XSSFCell.CELL_TYPE_NUMERIC:
					if("@".equals(cell.getCellStyle().getDataFormatString())){
						value = df.format(cell.getNumericCellValue());
//						System.out.println(i + "行" + j + "列  is :" + value);
					} else if ("General".equals(cell.getCellStyle().getDataFormatString())){
						value = nf.format(cell.getNumericCellValue());
						long longVal = Math.round(cell.getNumericCellValue());  
						if (Double.parseDouble(longVal + ".0") == Double.parseDouble((String) value)) { 
							value = longVal;  
						}else{
//							value = value;  
						}
//						System.out.println(i + "行" + j + "列  is :" + value);
					} else {
						value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
//						System.out.println(i + "行" + j + "列  is :" + value);
					}
					break;
				case XSSFCell.CELL_TYPE_BOOLEAN:
					value = cell.getBooleanCellValue();
//					System.out.println(i + "行" + j + "列  is :" + value);
					break;
				case XSSFCell.CELL_TYPE_BLANK:
					value = " ";
//					System.out.println(i + "行" + j + "列  is :" + value);
					break;
				default:
					value = cell.toString(); 
//					System.out.println(i + "行" + j + "列  is :" + value);
				}
				if(null == value || "".equals(value)){
					continue;
				}
				linked.add(value);
			}
			list.add(linked);
		}
		return list;
	}


}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章