Apache POI提供了操作microsoft documnent的java API,本文主要介绍HSSFWorkbook如何操作Excel文档。
HSSF是Horrible SpreadSheet Format的简称,主要用来读取和写入Excel文档
一,引入poi依赖
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.0.1</version> </dependency>
二,写入数据到Excel中
编程步骤:
(1)实例化HSSFWorkbook对象
(2)创建sheet页,行,单元格并设置其中的值
(3)实例化文件输出流FileOutputStream
1 public static void writeDataToExcel() { 2 3 HSSFWorkbook wb = new HSSFWorkbook(); 4 //创建sheet页 5 HSSFSheet sheet = wb.createSheet("学生表"); 6 //创建行 7 HSSFRow row0 = sheet.createRow(0); 8 //创建单元格 9 HSSFCell cell0 = row0.createCell(0); 10 //往单元格中设置值 11 cell0.setCellValue("学生成绩表"); 12 //合并单元格 13 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3)); 14 15 //创建表格第一行 16 HSSFRow row1 = sheet.createRow(1); 17 row1.createCell(0).setCellValue("姓名"); 18 row1.createCell(1).setCellValue("性别"); 19 row1.createCell(2).setCellValue("科目"); 20 row1.createCell(3).setCellValue("成绩"); 21 22 HSSFRow row2 = sheet.createRow(2); 23 row2.createCell(0).setCellValue("小琦"); 24 row2.createCell(1).setCellValue("男"); 25 row2.createCell(2).setCellValue("数据结构"); 26 row2.createCell(3).setCellValue("100"); 27 28 ...... 29 30 FileOutputStream outputStream = null; 31 try { 32 outputStream = new FileOutputStream("E:\\test.xls"); 33 //输出到excel文件中 34 wb.write(outputStream); 35 outputStream.flush(); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } finally { 39 try { 40 outputStream.close(); 41 wb.close(); 42 } catch (IOException e) { 43 e.printStackTrace(); 44 } 45 } 46 47 }
返回结果:
三,读取Excel文档中的数据
编程步骤:
(1)实例化文件输入流FileInputStream
(2)实例化HSSFWorkbook对象
(3)使用getSheetAt获取sheet页,遍历并获取单元格中的值
1 public static List<Student> readFromExcel(String filePath) { 2 3 FileInputStream fileInputStream = null; 4 HSSFWorkbook workbook = null; 5 6 List<Student> studentList = new ArrayList<>(); 7 try { 8 fileInputStream = new FileInputStream(filePath); 9 10 workbook = new HSSFWorkbook(fileInputStream); 11 12 //获取excel文档中第一个表单 13 HSSFSheet sheet = workbook.getSheetAt(0); 14 //遍历返回的结果 15 for (Row row : sheet) { 16 //从数据行开始读取 17 if (row.getRowNum() < 2) { 18 continue; 19 } 20 Student stu = new Student(); 21 stu.setName(row.getCell(0).getStringCellValue()); 22 stu.setGender(row.getCell(1).getStringCellValue()); 23 stu.setSubjectName(row.getCell(2).getStringCellValue()); 24 stu.setGrade(row.getCell(3).getStringCellValue()); 25 studentList.add(stu); 26 } 27 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } finally { 31 try { 32 workbook.close(); 33 fileInputStream.close(); 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } 37 } 38 39 return studentList; 40 }
四,总结:
利用HSSFWorkbook的 createSheet,createRow,createCell,setCellValue,getSheetAt,getCell,getStringCellValue等
这些方法可以很方便的操作Excel文档,从而完成像表格文件导入或导出的功能。