这里有两个例子,分别演示如何使用Java读取和写入Excel 2007文件。
一、写入Excel 2007文件
import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class POIExcelWriteDemo1 { public static void main(String[] args) { try { Workbook wb = new XSSFWorkbook(); CreationHelper createHelper = wb.getCreationHelper(); Sheet sheet = wb.createSheet("第一页"); // 创建行 Row row = sheet.createRow((short) 0); // 创建单元格,方法1 Cell cell = row.createCell(0); cell.setCellValue(1); // 直接创建单元格,方法2 row.createCell(1).setCellValue(1.2); row.createCell(2).setCellValue(createHelper.createRichTextString("你好我是Bug315")); row.createCell(3).setCellValue(createHelper.createRichTextString("www.hxstrive.com")); row.createCell(4).setCellValue(true); // 写入文件 FileOutputStream fileOut; fileOut = new FileOutputStream("bug315.xlsx"); wb.write(fileOut); fileOut.close(); System.out.println("写入成功,运行结束!"); } catch (Exception e) { e.printStackTrace(); } } }
二、读取Excel 2007文件数据
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.usermodel.WorkbookFactory; public class POIExcelReadDemo1 { public static void main(String[] args) { try { InputStream inp = new FileInputStream("bug315.xlsx"); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); for (Iterator rit = sheet.rowIterator(); rit.hasNext();) { Row row = (Row) rit.next(); // 迭代行 // 迭代单元格 for (Iterator cit = row.cellIterator(); cit.hasNext();) { Cell cell = (Cell) cit.next(); // 开始操作单元格(注意行和列是基于0索引的) // 在每一行的输出都打印如 "4:3 例子字符串",4:3代表第4行,第3列 System.out.print(cell.getRowIndex() + ":" + cell.getColumnIndex() + " "); // 打印单元格内的数据 switch (cell.getCellType()) { case Cell.CELL_TYPE_STRING: System.out.println(cell.getRichStringCellValue().getString()); break; case Cell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(cell)) { System.out.println(cell.getDateCellValue()); } else { System.out.println(cell.getNumericCellValue()); } break; case Cell.CELL_TYPE_BOOLEAN: System.out.println(cell.getBooleanCellValue()); break; case Cell.CELL_TYPE_FORMULA: System.out.println(cell.getCellFormula()); break; default: System.out.println(); } } } } catch (Exception e) { e.printStackTrace(); } } }