java poi读写excel

1、读取excel2003
	@Test
	//读取excel2003
	public void testCreateXLS(){
		try {
			String path = "f:\\app\\iotest\\n.xls.doc";
			String postfix = (path.trim().lastIndexOf(".") == -1)?"":path.substring(path.trim().lastIndexOf(".") + 1);
			if("xls".equalsIgnoreCase(postfix) || "xlsx".equalsIgnoreCase(postfix)){
				//创建工作簿
				HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(path));
				//创建sheet
				HSSFSheet sheet = wb.getSheetAt(0);
				StringBuffer sb = new StringBuffer();
				if(sheet != null){
					//sheet.getLastRowNum();最后一行
					for(int i=0;i<sheet.getLastRowNum();i++){
						if(sheet.getRow(i) != null){
							HSSFRow row = sheet.getRow(i);
							//row.getLastCellNum();一行中的最后一列
							for(int j=0;j<row.getLastCellNum();j++){
								HSSFCell cell = row.getCell(j);
								String cellValue = "";
								if(cell != null){
									switch(cell.getCellType()){
										case HSSFCell.CELL_TYPE_NUMERIC:
											cellValue = String.valueOf(cell.getNumericCellValue());
											break;
										case HSSFCell.CELL_TYPE_STRING:
											cellValue = cell.getStringCellValue();
											break;
										case HSSFCell.CELL_TYPE_BLANK:
											cellValue = cell.getStringCellValue();
											break;
										default:
											break;
									}
								}
								sb.append(cellValue.trim() + "  ");
							}
						}
						sb.append("\n");
					}
					System.out.println(sb.toString());
				}
				wb.close();
			}else{
				System.out.println("不支持的文件类型");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

猜你喜欢

转载自ntwjf.iteye.com/blog/2266148