Java POI 操作 Excel
Excel 文件组成
Excel对应一个workbook(HSSFWorkbook)。
workbook有多个sheet(HSSFSheet)
sheet有多个row(HSSFRow)
row有多个(HSSFCell)
基本操作步骤
-
HSSFWorkbook打开或创建Excel文件对象
-
HSSFWorkbook对象返回或创建Sheet对象
-
Sheet对象返回Row对象,Row对象得到Cell对象
-
读写Cell对象
//创建HSSFWorkbook对象 HSSFWorkbook workbook = new HSSFWorkbook(); //创建HSSFSheet对象 HSSFSheet sheet = workbook.createSheet("sheetTest"); //创建HSSFRow对象 HSSFRow row = sheet.createRow(2); //创建HSSFCell对象 HSSFCell cell = row.createCell(2); //设置单元格值 cell.setCellValue("Mr.周"); //输出文件 FileOutputStream outputStream = null; try { outputStream = new FileOutputStream("C:/Users/Xia/Desktop/TestFile.xls"); workbook.write(outputStream); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally { try { outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } }
-
pom.xml
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>