1. 程式人生 > >學習總結篇 java建立excle 解析excle (poi)

學習總結篇 java建立excle 解析excle (poi)

public static void main(String[] args) {
		
		try {
			//createWB();
			readExcle("e:\\woorbook.xls");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void createWB(){
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("學生資訊表");
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = row.createCell((short)0);
		cell.setCellValue("編號");
		row.createCell((short)1).setCellValue("姓名");
		row.createCell((short)2).setCellValue("性別");
		row.createCell((short)3).setCellValue("年齡");
		row.createCell((short)4).setCellValue("性別");
		row.createCell((short)5).setCellValue("班級");
		row.createCell((short)6).setCellValue("住址");
		row.createCell((short)7).setCellValue("入學日期");
		HSSFCellStyle cellStyle = workbook.createCellStyle();
		cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));

		for(int i=1;i<=5;i++){
			row = sheet.createRow((short)i);
			createCell(workbook, row, (short)0, String.valueOf(i));
			createCell(workbook, row, (short)1, "姓名"+i);
			createCell(workbook, row, (short)2, "性別"+i);
			createCell(workbook, row, (short)3, "年齡"+i);
			createCell(workbook, row, (short)4, "性別"+i);
			createCell(workbook, row, (short)5, "班級"+i);
			createCell(workbook, row, (short)6, "住址"+i);
			createCell(workbook, row, (short)7, new Date().toLocaleString());
		}
		try {
			FileOutputStream stream = new FileOutputStream("e:\\woorbook.xls");
			workbook.write(stream);
			stream.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	public static void createCell(HSSFWorkbook wb,HSSFRow row,short i,String value){
		HSSFCell cell = row.createCell(i);
		cell.setCellValue(value);
		HSSFCellStyle cellStyle = wb.createCellStyle();
		cellStyle.setAlignment((short)10);
		cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
		cell.setCellStyle(cellStyle);
	}
	
	public static void readExcle(String path) throws Exception{
		HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(path));
		for(int sheetindex = 0 ; sheetindex<workbook.getNumberOfSheets();sheetindex++){
			HSSFSheet sheet = workbook.getSheetAt(sheetindex);
			if(sheet != null){
				  for (int rowNumOfSheet = 0; rowNumOfSheet <= sheet.getLastRowNum(); rowNumOfSheet++) { 
					  HSSFRow row = sheet.getRow(rowNumOfSheet);
					  if(row != null){
						  for(int cellindex = 0;cellindex<= row.getLastCellNum();cellindex++){
							  HSSFCell cell = row.getCell((short)cellindex);
							  if(cell != null){
								  switch(cell.getCellType()){
								   case 0:
									   String cellVal1 = cell.getStringCellValue();
									   System.out.println(cellVal1);
									   break;
								   case 1:
									   String cellVal = cell.getStringCellValue();
									   System.out.println(cellVal);
									   break;
								  }
							  }
						  }
					  }
				  }
			}
		}
		
	}