1. 程式人生 > >Groovy 讀取excel檔案

Groovy 讀取excel檔案

用Apache的POI組建讀取Excel檔案

相關jar包:http://poi.apache.org/download.html#POI-3.8

class UpdateResourceDate {

	def fileUrl = "E:\\www\\updateRes\\過期時間批量更新.xls";
	
	void updateResourceDate(){
		FileInputStream is = new FileInputStream(fileUrl);
		HSSFWorkbook workbook = new HSSFWorkbook(is);
		workbook.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
		
		//迴圈sheet
		(0..<workbook.getSheets().iterator().collect {return it}
[email protected]
).each {s-> HSSFSheet sheet = workbook.getSheetAt(s); int rows = sheet.physicalNumberOfRows; //忽略第一行,標題行 (1..<rows).each{r-> HSSFRow row = sheet.getRow(r); def cells = row.physicalNumberOfCells; (0..<cells).each{c-> HSSFCell cell = row.getCell(c); if (c==4 || c==5) { print " "+getDataCellVal(cell); }else{ print " "+getCellVal(cell); } } println ""; } } } //取得日期列 def getDataCellVal(HSSFCell cell) { Date date = cell.getDateCellValue(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); return format.format(date); } def getCellVal(HSSFCell cell) { if (cell.getCellType() == HSSFCell.CELL_TYPE_BLANK) { return "" } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) { return cell.getBooleanCellValue(); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_ERROR) { return cell.getErrorCellValue(); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) { return cell.getNumericCellValue(); } else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) { return cell.getStringCellValue(); } else { return cell.getStringCellValue(); } } static main(args) { UpdateResourceDate a = new UpdateResourceDate(); a.updateResourceDate(); } }

上面的讀取Excel部分,為了當我們按Alt+/的時候有函式提示(Eclipse開發),所以寫得稍繁瑣,

再來個簡單點的:

//迴圈sheet
		workbook.getSheets().each {sheet->
			//迴圈行
			sheet.eachWithIndex {row, index->
				if (index>0) {//忽略第一行,標題行
					def cells = row.physicalNumberOfCells;//取得列數
					
					String resId = "";
					def date = "";
					String name = "";
					
					resId = getCellVal(row.getCell(0)).toString();
					
					name = getCellVal(row.getCell(1)).toString();
					date = getDateCellVal(row.getCell(5)).toString();
					
					println resId + "," + name + "," + date;					
				}	
			}			
		}