• Apache POI详解


    一 :简介


      开发中经常会设计到excel的处理,如导出Excel,导入Excel到数据库中,操作Excel目前有两个框架,一个是apache 的poi, 另一个是 Java Excel

      Apache POI 简介是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office(Excel、WORD、PowerPoint、Visio等)格式档案读和写的功能。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“可怜的模糊实现”。

      官方主页: http://poi.apache.org/index.html
      API文档: http://poi.apache.org/apidocs/index.html

      Java Excel是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件。jxl 由于其小巧 易用的特点, 逐渐已经取代了 POI-excel的地位, 成为了越来越多的java开发人员生成excel文件的首选。

      由于apache poi 在项目中用的比较多,本篇博客只讲解apache poi,不讲jxl

    二:Apache POI常用的类


      HSSF - 提供读写Microsoft Excel XLS格式档案的功能。
      XSSF - 提供读写Microsoft Excel OOXML XLSX格式档案的功能。
      HWPF - 提供读写Microsoft Word DOC97格式档案的功能。
      XWPF - 提供读写Microsoft Word DOC2003格式档案的功能。
      HSLF - 提供读写Microsoft PowerPoint格式档案的功能。
      HDGF - 提供读Microsoft Visio格式档案的功能。
      HPBF - 提供读Microsoft Publisher格式档案的功能。
      HSMF - 提供读Microsoft Outlook格式档案的功能。


      在开发中我们经常使用HSSF用来操作Excel处理表格数据,对于其它的不经常使用。

      HSSF 是Horrible SpreadSheet Format的缩写,通过HSSF,你可以用纯Java代码来读取、写入、修改Excel文件。HSSF 为读取操作提供了两类API:usermodel和eventusermodel,即“用户模型”和“事件-用户模型”。

    常用的类和方法


    HSSFWorkbook :工作簿,代表一个excel的整个文档
      HSSFWorkbook(); // 创建一个新的工作簿
      HSSFWorkbook(InputStream inputStream); // 创建一个关联输入流的工作簿,可以将一个excel文件封装成工作簿
      HSSFSheet createSheet(String sheetname); 创建一个新的Sheet
      HSSFSheet getSheet(String sheetName); 通过名称获取Sheet
      HSSFSheet getSheetAt(int index); // 通过索引获取Sheet,索引从0开始
      HSSFCellStyle createCellStyle(); 创建单元格样式
      int getNumberOfSheets(); 获取sheet的个数
      setActiveSheet(int index); 设置默认选中的工作表
      write();
      write(File newFile);
      write(OutputStream stream);
    HSSFSheet:工作表
      HSSFRow createRow(int rownum); 创建新行,需要指定行号,行号从0开始
      HSSFRow getRow(int index); 根据索引获取指定的行
      int addMergedRegion(CellRangeAddress region); 合并单元格
      CellRangeAddress(int firstRow, int lastRow, int firstCol, int lastCol); 单元格范围, 用于合并单元格,需要指定要合并的首行、最后一行、首列、最后一列。
      autoSizeColumn(int column); 自动调整列的宽度来适应内容
      getLastRowNum(); 获取最后的行的索引,没有行或者只有一行的时候返回0
      setColumnWidth(int columnIndex, int width); 设置某一列的宽度,width=字符个数 * 256,例如20个字符的宽度就是20 * 256
    HSSFRow :行
      HSSFCell createCell(int column); 创建新的单元格
      HSSFCell setCell(shot index);
      HSSFCell getCell(shot index);
      setRowStyle(HSSFCellStyle style); 设置行样式
      short getLastCellNum(); 获取最后的单元格号,如果单元格有第一个开始算,lastCellNum就是列的个数
      setHeightInPoints(float height); 设置行的高度
    HSSFCell:单元格
      setCellValue(String value); 设置单元格的值
      setCellType(); 设置单元格类型,如 字符串、数字、布尔等
      setCellStyle(); 设置单元格样式
      String getStringCellValue(); 获取单元格中的字符串值
      setCellStyle(HSSFCellStyle style); 设置单元格样式,例如字体、加粗、格式化
      setCellFormula(String formula); 设置计算公式,计算的结果作为单元格的值,也提供了异常常用的函数,如求和"sum(A1,C1)"、日期函数、字符串相关函数、CountIf和SumIf函数、随机数函数等
    HSSFCellStyle :单元格样式
      setFont(Font font); 为单元格设置字体样式
      setAlignment(HorizontalAlignment align); // 设置水平对齐方式
      setVerticalAlignment(VerticalAlignment align); // 设置垂直对齐方式
      setFillPattern(FillPatternType fp);
      setFillForegroundColor(short bg); 设置前景色
      setFillBackgroundColor(short bg); 设置背景颜色
    HSSFFont:字体
      setColor(short color); // 设置字体颜色
      setBold(boolean bold); // 设置是否粗体
      setItalic(boolean italic); 设置倾斜
      setUnderline(byte underline); 设置下划线
    HSSFName:名称
    HSSFDataFormat :日期格式化
    HSSFHeader : Sheet的头部
    HSSFFooter :Sheet的尾部
    HSSFDateUtil :日期工具
    HSSFPrintSetup :打印设置
    HSSFErrorConstants:错误信息表


    Excel中的工作簿、工作表、行、单元格中的关系:

    一个Excel文件对应于一个workbook(HSSFWorkbook),
    一个workbook可以有多个sheet(HSSFSheet)组成,
    一个sheet是由多个row(HSSFRow)组成,
    一个row是由多个cell(HSSFCell)组成


    三:基础示例


    首先引入apache poi的依赖

    1 <dependency> 
    2 <groupId>org.apache.poi</groupId> 
    3 <artifactId>poi</artifactId> 
    4 <version>3.8</version> 
    5 </dependency>


    示例一:在桌面上生成一个Excel文件

     1 public static void createExcel() throws IOException{
     2 // 获取桌面路径
     3 FileSystemView fsv = FileSystemView.getFileSystemView();
     4 String desktop = fsv.getHomeDirectory().getPath();
     5 String filePath = desktop + "/template.xls";
     6 
     7 File file = new File(filePath);
     8 OutputStream outputStream = new FileOutputStream(file);
     9 HSSFWorkbook workbook = new HSSFWorkbook();
    10 HSSFSheet sheet = workbook.createSheet("Sheet1");
    11 HSSFRow row = sheet.createRow(0);
    12 row.createCell(0).setCellValue("id");
    13 row.createCell(1).setCellValue("订单号");
    14 row.createCell(2).setCellValue("下单时间");
    15 row.createCell(3).setCellValue("个数");
    16 row.createCell(4).setCellValue("单价");
    17 row.createCell(5).setCellValue("订单金额");
    18 row.setHeightInPoints(30); // 设置行的高度
    19 
    20 HSSFRow row1 = sheet.createRow(1);
    21 row1.createCell(0).setCellValue("1");
    22 row1.createCell(1).setCellValue("NO00001");
    23 
    24 // 日期格式化
    25 HSSFCellStyle cellStyle2 = workbook.createCellStyle();
    26 HSSFCreationHelper creationHelper = workbook.getCreationHelper();
    27 cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
    28 sheet.setColumnWidth(2, 20 * 256); // 设置列的宽度
    29 
    30 HSSFCell cell2 = row1.createCell(2);
    31 cell2.setCellStyle(cellStyle2);
    32 cell2.setCellValue(new Date());
    33 
    34 row1.createCell(3).setCellValue(2);
    35 
    36 
    37 // 保留两位小数
    38 HSSFCellStyle cellStyle3 = workbook.createCellStyle();
    39 cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
    40 HSSFCell cell4 = row1.createCell(4);
    41 cell4.setCellStyle(cellStyle3);
    42 cell4.setCellValue(29.5);
    43 
    44 
    45 // 货币格式化
    46 HSSFCellStyle cellStyle4 = workbook.createCellStyle();
    47 HSSFFont font = workbook.createFont();
    48 font.setFontName("华文行楷");
    49 font.setFontHeightInPoints((short)15);
    50 font.setColor(HSSFColor.RED.index);
    51 cellStyle4.setFont(font);
    52 
    53 HSSFCell cell5 = row1.createCell(5);
    54 cell5.setCellFormula("D2*E2"); // 设置计算公式
    55 
    56 // 获取计算公式的值
    57 HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
    58 cell5 = e.evaluateInCell(cell5);
    59 System.out.println(cell5.getNumericCellValue());
    60 
    61 
    62 workbook.setActiveSheet(0);
    63 workbook.write(outputStream);
    64 outputStream.close();
    65 }

    示例2:读取Excel,解析数据

     1 public static void readExcel() throws IOException{
     2 FileSystemView fsv = FileSystemView.getFileSystemView();
     3 String desktop = fsv.getHomeDirectory().getPath();
     4 String filePath = desktop + "/template.xls";
     5 
     6 FileInputStream fileInputStream = new FileInputStream(filePath);
     7 BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
     8 POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
     9 HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
    10 HSSFSheet sheet = workbook.getSheet("Sheet1");
    11 
    12 int lastRowIndex = sheet.getLastRowNum();
    13 System.out.println(lastRowIndex);
    14 for (int i = 0; i <= lastRowIndex; i++) {
    15 HSSFRow row = sheet.getRow(i);
    16 if (row == null) { break; }
    17 
    18 short lastCellNum = row.getLastCellNum();
    19 for (int j = 0; j < lastCellNum; j++) {
    20 String cellValue = row.getCell(j).getStringCellValue();
    21 System.out.println(cellValue);
    22 }
    23 }
    24 
    25 bufferedInputStream.close();
    26 }

    四:Java Web 中导出和导入Excel


    1、导出示例

     1 @SuppressWarnings("resource")
     2 @RequestMapping("/export") 
     3 public void exportExcel(HttpServletResponse response, HttpSession session, String name) throws Exception { 
     4 
     5 String[] tableHeaders = {"id", "姓名", "年龄"}; 
     6 
     7 HSSFWorkbook workbook = new HSSFWorkbook();
     8 HSSFSheet sheet = workbook.createSheet("Sheet1");
     9 HSSFCellStyle cellStyle = workbook.createCellStyle(); 
    10 cellStyle.setAlignment(HorizontalAlignment.CENTER); 
    11 cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
    12 
    13 Font font = workbook.createFont(); 
    14 font.setColor(HSSFColor.RED.index); 
    15 font.setBold(true);
    16 cellStyle.setFont(font);
    17 
    18 // 将第一行的三个单元格给合并
    19 sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
    20 HSSFRow row = sheet.createRow(0);
    21 HSSFCell beginCell = row.createCell(0);
    22 beginCell.setCellValue("通讯录");    
    23 beginCell.setCellStyle(cellStyle);
    24 
    25 row = sheet.createRow(1);
    26 // 创建表头
    27 for (int i = 0; i < tableHeaders.length; i++) {
    28 HSSFCell cell = row.createCell(i);
    29 cell.setCellValue(tableHeaders[i]);
    30 cell.setCellStyle(cellStyle); 
    31 }
    32 
    33 List<User> users = new ArrayList<>();
    34 users.add(new User(1L, "张三", 20));
    35 users.add(new User(2L, "李四", 21));
    36 users.add(new User(3L, "王五", 22));
    37 
    38 for (int i = 0; i < users.size(); i++) {
    39 row = sheet.createRow(i + 2);
    40 
    41 User user = users.get(i);
    42 row.createCell(0).setCellValue(user.getId()); 
    43 row.createCell(1).setCellValue(user.getName()); 
    44 row.createCell(2).setCellValue(user.getAge()); 
    45 }
    46 
    47 OutputStream outputStream = response.getOutputStream(); 
    48 response.reset(); 
    49 response.setContentType("application/vnd.ms-excel"); 
    50 response.setHeader("Content-disposition", "attachment;filename=template.xls");
    51 
    52 workbook.write(outputStream);
    53 outputStream.flush(); 
    54 outputStream.close();
    55 }

    2、导入示例


      1、使用SpringMVC上传文件,需要用到commons-fileupload

      

    1 <dependency>
    2 <groupId>commons-fileupload</groupId>
    3 <artifactId>commons-fileupload</artifactId>
    4 <version>1.3</version>
    5 </dependency>

      2、需要在spring的配置文件中配置一下multipartResolver

    1 <bean name="multipartResolver" 
    2 class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    3 <property name="defaultEncoding" value="UTF-8" />
    4 </bean>

      3、index.jsp

    1 <a href="/Spring-Mybatis-Druid/user/export">导出</a> <br/>
    2 
    3 <form action="/Spring-Mybatis-Druid/user/import" enctype="multipart/form-data" method="post">
    4     <input type="file" name="file"/> 
    5     <input type="submit" value="导入Excel">
    6 </form>

      4、解析上传的.xls文件

     1 @SuppressWarnings("resource")
     2 @RequestMapping("/import")
     3 public void importExcel(@RequestParam("file") MultipartFile file) throws Exception{
     4 InputStream inputStream = file.getInputStream();
     5 BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
     6 POIFSFileSystem fileSystem = new POIFSFileSystem(bufferedInputStream);
     7 HSSFWorkbook workbook = new HSSFWorkbook(fileSystem);
     8 //HSSFWorkbook workbook = new HSSFWorkbook(file.getInputStream());
     9 HSSFSheet sheet = workbook.getSheetAt(0);
    10 
    11 int lastRowNum = sheet.getLastRowNum();
    12 for (int i = 2; i <= lastRowNum; i++) {
    13 HSSFRow row = sheet.getRow(i);
    14 int id = (int) row.getCell(0).getNumericCellValue();
    15 String name = row.getCell(1).getStringCellValue();
    16 int age = (int) row.getCell(2).getNumericCellValue();
    17 
    18 System.out.println(id + "-" + name + "-" + age);
    19 }
    20 }

    项目示例代码下载地址:

    http://download.csdn.net/detail/vbirdbest/9861536

    ————————————————
    版权声明:本文为CSDN博主「vbirdbest」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/vbirdbest/article/details/72870714

  • 相关阅读:
    ACR2010_TNF拮抗剂促进SpA患者椎体侵蚀的修复
    2010年10月第1期(ACR2010专刊AS篇)_中信国健临床通讯目录
    ACR2010_中轴型SpA患者使用TNF拮抗剂治疗后放射学进展与全身炎症消退相关
    ACR2010_小剂量依那西普对达到缓解的AS患者有效
    ACR2010_在高风险人群中应用新版RA分类标准可能发现更多临床前RA
    ACR2010_常规医疗环境下TNF拮抗剂对RA骨侵蚀的修复作用
    ACR2010_HLA B27阳性的极早期AS患者停用TNF拮抗剂后疗效持续: 3个月随机安慰剂对照试验后随访40周
    .net委托与事件 中庸
    筛选法因子之和
    POJ2488 A Knight's Journey 解题报告
  • 原文地址:https://www.cnblogs.com/dream-by-dream/p/12100347.html
Copyright © 2020-2023  润新知