标签:style blog http io os ar 使用 java for
对于一个程序员来说,文件操作是经常遇到的,尤其是对Excel文件的操作。
在这里介绍一下我在项目中用到的一个操作Excel的工具——POI。关于POI的一些概念,网络上很多,详细信息大家可以自行百度,我在这里只做简单介绍。POI是apache的类库,主要是为java开发人员提供对Office文件(word、ppt、Excel)处理的支持。我这里主要给出几个例子来说明演示一下。
准备工作
我用的版本是3.10.1,需要的jar有:
public void testReadExcel() { try { // 读取Excel Workbook wb = new HSSFWorkbook(new FileInputStream("d:\\2.xls")); // 获取sheet数目 for (int t = 0; t < wb.getNumberOfSheets(); t++) { Sheet sheet = wb.getSheetAt(t); Row row = null; int lastRowNum = sheet.getLastRowNum(); // 循环读取 for (int i = 0; i <= lastRowNum; i++) { row = sheet.getRow(i); if (row != null) { // 获取每一列的值 for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); String value = getCellValue(cell) ; if(!value.equals("")){ System.out.print(value + " | "); } } System.out.println(); } } } } catch (Exception e) { e.printStackTrace(); } }
/*** * 读取单元格的值 * * @Title: getCellValue * @Date : 2014-9-11 上午10:52:07 * @param cell * @return */ private String getCellValue(Cell cell) { Object result = ""; if (cell != null) { switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: result = cell.getStringCellValue(); break; case Cell.CELL_TYPE_NUMERIC: result = cell.getNumericCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: result = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_FORMULA: result = cell.getCellFormula(); break; case Cell.CELL_TYPE_ERROR: result = cell.getErrorCellValue(); break; case Cell.CELL_TYPE_BLANK: break; default: break; } } return result.toString(); }
public void testWriteExcel() { String excelPath = "d:/3.xls"; Workbook workbook = null; try { // XSSFWorkbook used for .xslx (>= 2007), HSSWorkbook for 03 .xsl workbook = new HSSFWorkbook();// XSSFWorkbook();//WorkbookFactory.create(inputStream); } catch (Exception e) { System.out.println("创建Excel失败: "); e.printStackTrace(); } if (workbook != null) { Sheet sheet = workbook.createSheet("测试数据"); Row row0 = sheet.createRow(0); for (int i = 0; i < 6; i++) { Cell cell = row0.createCell(i, Cell.CELL_TYPE_STRING); cell.setCellValue("列标题" + i ); //sheet.autoSizeColumn(i);//自动调整宽度 } for (int rowNum = 1; rowNum < 10; rowNum++) { Row row = sheet.createRow(rowNum); for (int i = 0; i < 6; i++) { Cell cell = row.createCell(i, Cell.CELL_TYPE_STRING); cell.setCellValue("单元格" + String.valueOf(rowNum + 1) + String.valueOf(i + 1)); } } try { FileOutputStream outputStream = new FileOutputStream(excelPath); workbook.write(outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { System.out .println("写入Excel失败: "); e.printStackTrace(); } } }效果图如下:
标签:style blog http io os ar 使用 java for
原文地址:http://blog.csdn.net/xiaoxian8023/article/details/40562993