【Java】使用Apache POI生成和解析Excel文件

原文 http://www.cnblogs.com/h--d/p/6735110.html



概述

  Excel是我们平时工作中比较常用的用于存储二维表数据的,JAVA也可以直接对Excel进行操作,分别有jxl和poi,2种方式。

  HSSF is the POI Project's pure Java implementation of the Excel '97(-2007) file format. XSSF is the POI Project's pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.
  从官方文档中了解到:POI提供的HSSF包用于操作 Excel '97(-2007)的.xls文件,而XSSF包则用于操作Excel2007之后的.xslx文件。

  本片文章主要参考poi官网:http://poi.apache.org/index.html

代码

  •    要使用poi,必须引入poi的jar包,maven依赖如下:

 1 <dependency>
 2     <groupId>org.apache.poi</groupId>
 3     <artifactId>poi</artifactId>
 4     <version>3.14</version>
 5 </dependency>
 6 
 7 <dependency>
 8     <groupId>org.apache.poi</groupId>
 9     <artifactId>poi-ooxml</artifactId>
10     <version>3.14</version>
11 </dependency>
12 <dependency>
13     <groupId>org.apache.poi</groupId>
14     <artifactId>poi-ooxml-schemas</artifactId>
15     <version>3.14</version>
16 </dependency>

  •   使用poi创建execl文件

      1 package test.hd.poi;
      2 
      3 import java.io.FileOutputStream;
      4 import java.io.IOException;
      5 import java.util.Date;
      6 
      7 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      8 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
      9 import org.apache.poi.ss.usermodel.Cell;
     10 import org.apache.poi.ss.usermodel.CellStyle;
     11 import org.apache.poi.ss.usermodel.ClientAnchor;
     12 import org.apache.poi.ss.usermodel.Comment;
     13 import org.apache.poi.ss.usermodel.CreationHelper;
     14 import org.apache.poi.ss.usermodel.DataFormat;
     15 import org.apache.poi.ss.usermodel.Drawing;
     16 import org.apache.poi.ss.usermodel.Font;
     17 import org.apache.poi.ss.usermodel.RichTextString;
     18 import org.apache.poi.ss.usermodel.Row;
     19 import org.apache.poi.ss.usermodel.Sheet;
     20 import org.apache.poi.ss.usermodel.Workbook;
     21 import org.apache.poi.ss.util.CellRangeAddress;
     22 
     23 public class CreateExcel {
     24 
     25     public static void main(String[] args) throws IOException, InterruptedException {
     26         Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
     27         for (int i = 0; i < wbs.length; i++) {
     28             Workbook workbook = wbs[i];
     29             // 得到一个POI的工具类
     30             CreationHelper createHelper = workbook.getCreationHelper();
     31 
     32             // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
     33             Sheet sheet = workbook.createSheet();
     34             // Sheet sheet = workbook.createSheet("SheetName");
     35 
     36             // 用于格式化单元格的数据
     37             DataFormat format = workbook.createDataFormat();
     38 
     39             // 设置字体
     40             Font font = workbook.createFont();
     41             font.setFontHeightInPoints((short) 20); // 字体高度
     42             font.setColor(Font.COLOR_RED); // 字体颜色
     43             font.setFontName("黑体"); // 字体
     44             font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 宽度
     45             font.setItalic(true); // 是否使用斜体
     46             // font.setStrikeout(true); //是否使用划线
     47 
     48             // 设置单元格类型
     49             CellStyle cellStyle = workbook.createCellStyle();
     50             cellStyle.setFont(font);
     51             cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
     52             cellStyle.setWrapText(true);
     53 
     54             CellStyle cellStyle2 = workbook.createCellStyle();
     55             cellStyle2.setDataFormat(format.getFormat("#, ## 0.0"));
     56 
     57             CellStyle cellStyle3 = workbook.createCellStyle();
     58             cellStyle3.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm:ss"));
     59 
     60             // 添加单元格注释
     61             // 创建Drawing对象,Drawing是所有注释的容器.
     62             Drawing drawing = sheet.createDrawingPatriarch();
     63             // ClientAnchor是附属在WorkSheet上的一个对象, 其固定在一个单元格的左上角和右下角.
     64             ClientAnchor anchor = createHelper.createClientAnchor();
     65             // 设置注释位子
     66             anchor.setRow1(0);
     67             anchor.setRow2(2);
     68             anchor.setCol1(0);
     69             anchor.setCol2(2);
     70             // 定义注释的大小和位置,详见文档
     71             Comment comment = drawing.createCellComment(anchor);
     72             // 设置注释内容
     73             RichTextString str = createHelper.createRichTextString("Hello, World!");
     74             comment.setString(str);
     75             // 设置注释作者. 当鼠标移动到单元格上是可以在状态栏中看到该内容.
     76             comment.setAuthor("H__D");
     77 
     78             // 定义几行
     79             for (int rownum = 0; rownum < 30; rownum++) {
     80                 // 创建行
     81                 Row row = sheet.createRow(rownum);
     82                 // 创建单元格
     83                 Cell cell = row.createCell((short) 1);
     84                 cell.setCellValue(createHelper.createRichTextString("Hello!" + rownum));// 设置单元格内容
     85                 cell.setCellStyle(cellStyle);// 设置单元格样式
     86                 cell.setCellType(Cell.CELL_TYPE_STRING);// 指定单元格格式:数值、公式或字符串
     87                 cell.setCellComment(comment);// 添加注释
     88 
     89                 // 格式化数据
     90                 Cell cell2 = row.createCell((short) 2);
     91                 cell2.setCellValue(11111.25);
     92                 cell2.setCellStyle(cellStyle2);
     93 
     94                 Cell cell3 = row.createCell((short) 3);
     95                 cell3.setCellValue(new Date());
     96                 cell3.setCellStyle(cellStyle3);
     97 
     98                 sheet.autoSizeColumn((short) 0); // 调整第一列宽度
     99                 sheet.autoSizeColumn((short) 1); // 调整第二列宽度
    100                 sheet.autoSizeColumn((short) 2); // 调整第三列宽度
    101                 sheet.autoSizeColumn((short) 3); // 调整第四列宽度
    102 
    103             }
    104 
    105             // 合并单元格
    106             sheet.addMergedRegion(new CellRangeAddress(1, // 第一行(0)
    107                     2, // last row(0-based)
    108                     1, // 第一列(基于0)
    109                     2 // 最后一列(基于0)
    110             ));
    111 
    112             // 保存
    113             String filename = "C:/Users/H__D/Desktop/workbook.xls";
    114             if (workbook instanceof XSSFWorkbook) {
    115                 filename = filename + "x";
    116             }
    117 
    118             FileOutputStream out = new FileOutputStream(filename);
    119             workbook.write(out);
    120             out.close();
    121         }
    122     }
    123 
    124 }

     

  • 使用poi修改execl文件

     1 package test.hd.poi;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.InputStream;
     7 
     8 import org.apache.poi.EncryptedDocumentException;
     9 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    10 import org.apache.poi.ss.usermodel.Cell;
    11 import org.apache.poi.ss.usermodel.Row;
    12 import org.apache.poi.ss.usermodel.Sheet;
    13 import org.apache.poi.ss.usermodel.Workbook;
    14 import org.apache.poi.ss.usermodel.WorkbookFactory;
    15 
    16 
    17 
    18 public class UpdateExcel {
    19     
    20     public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
    21         
    22         InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    23         //InputStream inp = new FileInputStream("workbook.xlsx");
    24 
    25         Workbook workbook = WorkbookFactory.create(inputStream);
    26         Sheet sheet = workbook.getSheetAt(0);
    27         Row row = sheet.getRow(2);
    28         Cell cell = row.getCell(3);
    29         if (cell == null)
    30             cell = row.createCell(3);
    31         cell.setCellType(Cell.CELL_TYPE_STRING);
    32         cell.setCellValue("a test");
    33 
    34         // Write the output to a file
    35         FileOutputStream fileOut = new FileOutputStream("C:/Users/H__D/Desktop/workbook.xls");
    36         workbook.write(fileOut);
    37         fileOut.close();
    38         
    39     }
    40     
    41 }

     

  • 使用poi解析excel文件

     1 package test.hd.poi;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileOutputStream;
     5 import java.io.IOException;
     6 import java.io.InputStream;
     7 
     8 import org.apache.poi.EncryptedDocumentException;
     9 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    10 import org.apache.poi.ss.usermodel.Cell;
    11 import org.apache.poi.ss.usermodel.DataFormatter;
    12 import org.apache.poi.ss.usermodel.DateUtil;
    13 import org.apache.poi.ss.usermodel.Row;
    14 import org.apache.poi.ss.usermodel.Sheet;
    15 import org.apache.poi.ss.usermodel.Workbook;
    16 import org.apache.poi.ss.usermodel.WorkbookFactory;
    17 import org.apache.poi.ss.util.CellReference;
    18 
    19 import com.microsoft.schemas.office.visio.x2012.main.CellType;
    20 
    21 
    22 
    23 public class ReadExcel {
    24     
    25     public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
    26         
    27         InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    28         //InputStream inp = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    29 
    30         Workbook workbook = WorkbookFactory.create(inputStream);
    31         Sheet sheet = workbook.getSheetAt(0);
    32 
    33         DataFormatter formatter = new DataFormatter();
    34         for (Row row : sheet) {
    35             for (Cell cell : row) {
    36                 CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
    37                 //单元格名称
    38                 System.out.print(cellRef.formatAsString());
    39                 System.out.print(" - ");
    40 
    41                 //通过获取单元格值并应用任何数据格式(Date,0.00,1.23e9,$ 1.23等),获取单元格中显示的文本
    42                 String text = formatter.formatCellValue(cell);
    43                 System.out.println(text);
    44 
    45                  //获取值并自己格式化
    46                 switch (cell.getCellType()) {
    47                     case Cell.CELL_TYPE_STRING:// 字符串型
    48                         System.out.println(cell.getRichStringCellValue().getString());
    49                         break;
    50                     case Cell.CELL_TYPE_NUMERIC:// 数值型
    51                         if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值
    52                             System.out.println(cell.getDateCellValue());
    53                         } else {// 纯数字
    54                             System.out.println(cell.getNumericCellValue());
    55                         }
    56                         break;
    57                     case Cell.CELL_TYPE_BOOLEAN:// 布尔
    58                         System.out.println(cell.getBooleanCellValue());
    59                         break;
    60                     case Cell.CELL_TYPE_FORMULA:// 公式型
    61                         System.out.println(cell.getCellFormula());
    62                         break;
    63                     case Cell.CELL_TYPE_BLANK:// 空值
    64                         System.out.println();
    65                         break;
    66                     case Cell.CELL_TYPE_ERROR: // 故障
    67                         System.out.println();
    68                         break;
    69                     default:
    70                         System.out.println();
    71                 }
    72             }
    73         }
    74         
    75     }
    76     
    77 }





http://www.cnblogs.com/h--d/p/6735110.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很抱歉,我之前的回答可能有些误解您的问题。如果您想要获取生成Excel模板Java代码,那么需要使用另外的技术。 通常情况下,我们可以使用Excel模板引擎来生成Excel文档。比较常用的Excel模板引擎有Apache POI和Jxls。其中,Jxls是一款基于POI库的Excel模板引擎,可以方便地使用Excel模板生成Excel文档。 下面是使用Jxls生成Excel文档的一些基本步骤: 1. 准备Excel模板,可以使用Excel编辑器创建一个包含表头和数据区域的Excel文件。 2. 在Java代码中,使用Jxls API读取Excel模板文件,将数据填充到Excel模板中,并生成新的Excel文件。 下面是一个使用Jxls生成Excel文件的简单示例: ``` // 读取Excel模板 InputStream is = new FileInputStream("template.xlsx"); Workbook workbook = WorkbookFactory.create(is); // 准备数据 List<User> userList = new ArrayList<>(); userList.add(new User("张三", 20)); userList.add(new User("李四", 25)); userList.add(new User("王五", 30)); // 填充数据到Excel模板中 Map<String, Object> context = new HashMap<>(); context.put("userList", userList); JxlsHelper.getInstance().processTemplate(workbook, new FileOutputStream("output.xlsx"), context); ``` 在这个示例中,我们首先从Excel模板文件中读取工作簿对象,然后准备数据,将数据填充到Excel模板中,最后生成新的Excel文件。在数据填充过程中,我们可以使用Jxls提供的语法来访问和处理Excel模板中的单元格和区域。 需要注意的是,在使用Jxls生成Excel文件时,我们需要保证Excel模板中的表头和数据区域的位置和格式与Java代码中的数据结构和语法一致。只有这样,才能正确地填充数据并生成期望的Excel文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值