poi读excel2007

来源:互联网 发布:金税盘开票软件使用 编辑:程序博客网 时间:2024/06/05 04:55

以前做了很多东西都是jxl写excel文档的,但是,最近有需求要读入excel2007文件的内容,发现jxl对2007不支持,网上找了下,说jxl已经不更新了,但是apache的poi是可以支持的,所有就学了下,现贴出一段poi读取excel的代码,供大家参考,需要的poi的jar包文件,可以去我的空间下载poi,是最新的。代码是项目中的代码,大家可以复制后改动,如果有错误,请指正,谢谢!

/** * poi的方式读取excel2007 * @param strpath * @return */public String loadExcel2007(String strpath) {DecimalFormat df = new DecimalFormat("#0.00%");// 格式化数据XSSFWorkbook workbook = null;File tempDir = new File(strpath);if (!tempDir.exists()) {System.out.println(" the file not exist :" + strpath);}try {workbook = new XSSFWorkbook(new FileInputStream(strpath));// workbook.getNumberOfSheets();//可以获取sheet的数量if (null != workbook.getSheetAt(0)) {XSSFSheet asheet = workbook.getSheetAt(0); // 此处获取第一个sheetint rowNum = asheet.getLastRowNum();// 获取总行数for (int i = 1; i <= rowNum; i++) {XSSFRow aRow = asheet.getRow(i);int cellNum = aRow.getLastCellNum();// 获取本行的列数for (int j = 0; j < cellNum; j++) {String strCell = "";XSSFCell cell = aRow.getCell(0);if (cell != null) {int cellType = cell.getCellType();switch (cellType) {case 0:// NumericstrCell = df.format(cell.getNumericCellValue());break;case 1:// StringstrCell = cell.getStringCellValue();break;default:strCell = "无法读取格式"; // System.out.println("格式不对不读");//其它格式的数据}System.out.println(strCell);} else {System.out.println("空cell!");}}}}} catch (Exception e) {System.out.println("ReadExcelError" + e);} finally {if (workbook != null) {workbook = null;}}return "";}

 

pio读取excel2003,这个和读2003用的不是一个类,此处贴出一段代码

/** * poi读取excel2003 * @param strpath * @return */public String loadExcel2003(String strpath) {DecimalFormat df = new DecimalFormat("#0.00%");String correctTelephone = "";int correctnum = 0;// 统计通过验证的数目HSSFWorkbook workbook = null;try {workbook = new HSSFWorkbook(new FileInputStream(strpath));// workbook.getNumberOfSheets());//获取sheet数if (null != workbook.getSheetAt(0)) {HSSFSheet aSheet = workbook.getSheetAt(0);// 获得一个sheet// System.out.println("+++getFirstRowNum+++" +// aSheet.getFirstRowNum());//// System.out.println("+++getLastRowNum+++" +// aSheet.getLastRowNum());int rowNum = aSheet.getLastRowNum();// 获取总行数for (int i = 1; i <= rowNum; i++) {HSSFRow aRow = aSheet.getRow(i);int cellNum = aRow.getLastCellNum();// 获取本行的列数// aRow.getLastCellNum());for (int j = 0; j < cellNum; j++) {String strCell = "";HSSFCell cell = aRow.getCell(0);if (cell != null) {int cellType = cell.getCellType();switch (cellType) {case 0:// NumericstrCell = df.format(cell.getNumericCellValue());break;case 1:// StringstrCell = cell.getStringCellValue();break;default:strCell = "无法读取格式"; // 其它格式的数据}System.out.println(strCell);} else {System.out.println("cell内容为空!");}}}}} catch (Exception e) {System.out.println("ReadExcelError" + e);} finally {if (workbook != null) {workbook = null;}}return "";}

 

简略说明下,在读取字段的时候,需要简单的判断下,对于不同类型的应应该用不同的方式读取,如果常用数据库的理解应该比较简单,此例只用到数值型和字符串两种,所以处理的比较简

原创粉丝点击