使用POI包进行Excel文件操作(2)

来源:互联网 发布:汇通财经数据直播 编辑:程序博客网 时间:2024/06/06 12:47

 使用POI包读取Excel文件的内容:

一,构造工作簿对象

FileInputStream fis = null;try {// 构造文件输入流fis = new FileInputStream("d:\\temp.xls");} catch (FileNotFoundException e) {e.printStackTrace();System.exit(0);}HSSFWorkbook workbook = null;try {// 构造工作簿workbook = new HSSFWorkbook(fis);} catch (IOException e) {e.printStackTrace();System.exit(0);}try {// 关闭文件输入流fis.close();} catch (IOException e) {e.printStackTrace();}

 

二、读取并输出数据:

// 取得第一个工作表HSSFSheet sheet0 = workbook.getSheetAt(0);// 日期格式化器SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");// 迭代处理行for (Iterator<Row> rows = sheet0.rowIterator(); rows.hasNext();) {Row currentRow = rows.next();// 迭代处理单元格for (Iterator<Cell> cells = currentRow.iterator(); cells.hasNext();) {Cell currentCell = cells.next();// 取得当前单元格的数据类型int cellType = currentCell.getCellType();switch (cellType) {case HSSFCell.CELL_TYPE_NUMERIC:// 如果该单元格中存放的是日期值,获取单元格中的值并格式化后输出if (DateUtil.isCellDateFormatted(currentCell)) {System.out.print(sdf.format(currentCell.getDateCellValue()));} else {// 获取单元格中的数值输出if (currentCell.getCellStyle().getDataFormat() != 0) {System.out.print(String.format("%0$,5.2f",currentCell.getNumericCellValue()));} else {System.out.print(String.format("%d",(int) currentCell.getNumericCellValue()));}}break;case HSSFCell.CELL_TYPE_STRING:System.out.print(currentCell.getStringCellValue());break;case HSSFCell.CELL_TYPE_BOOLEAN:System.out.print(currentCell.getBooleanCellValue());break;}System.out.print("    ");}System.out.println();}System.out.println();



完毕。

原创粉丝点击