概述

  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. public class UpdateExcel {
    17.  
    18. public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
    19.  
    20. InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    21. //InputStream inp = new FileInputStream("workbook.xlsx");
    22.  
    23. Workbook workbook = WorkbookFactory.create(inputStream);
    24. Sheet sheet = workbook.getSheetAt(0);
    25. Row row = sheet.getRow(2);
    26. Cell cell = row.getCell(3);
    27. if (cell == null)
    28. cell = row.createCell(3);
    29. cell.setCellType(Cell.CELL_TYPE_STRING);
    30. cell.setCellValue("a test");
    31.  
    32. // Write the output to a file
    33. FileOutputStream fileOut = new FileOutputStream("C:/Users/H__D/Desktop/workbook.xls");
    34. workbook.write(fileOut);
    35. fileOut.close();
    36.  
    37. }
    38.  
    39. }
  • 使用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. public class ReadExcel {
    22.  
    23. public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
    24.  
    25. InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    26. //InputStream inp = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    27.  
    28. Workbook workbook = WorkbookFactory.create(inputStream);
    29. Sheet sheet = workbook.getSheetAt(0);
    30.  
    31. DataFormatter formatter = new DataFormatter();
    32. for (Row row : sheet) {
    33. for (Cell cell : row) {
    34. CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
    35. //单元格名称
    36. System.out.print(cellRef.formatAsString());
    37. System.out.print(" - ");
    38.  
    39. //通过获取单元格值并应用任何数据格式(Date,0.00,1.23e9,$ 1.23等),获取单元格中显示的文本
    40. String text = formatter.formatCellValue(cell);
    41. System.out.println(text);
    42.  
    43. //获取值并自己格式化
    44. switch (cell.getCellType()) {
    45. case Cell.CELL_TYPE_STRING:// 字符串型
    46. System.out.println(cell.getRichStringCellValue().getString());
    47. break;
    48. case Cell.CELL_TYPE_NUMERIC:// 数值型
    49. if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值
    50. System.out.println(cell.getDateCellValue());
    51. } else {// 纯数字
    52. System.out.println(cell.getNumericCellValue());
    53. }
    54. break;
    55. case Cell.CELL_TYPE_BOOLEAN:// 布尔
    56. System.out.println(cell.getBooleanCellValue());
    57. break;
    58. case Cell.CELL_TYPE_FORMULA:// 公式型
    59. System.out.println(cell.getCellFormula());
    60. break;
    61. case Cell.CELL_TYPE_BLANK:// 空值
    62. System.out.println();
    63. break;
    64. case Cell.CELL_TYPE_ERROR: // 故障
    65. System.out.println();
    66. break;
    67. default:
    68. System.out.println();
    69. }
    70. }
    71. }
    72.  
    73. }
    74.  
    75. }

【Java】使用Apache POI生成和解析Excel文件的更多相关文章

  1. Java中用Apache POI生成excel和word文档

    概述: 近期在做项目的过程中遇到了excel的数据导出和word的图文表报告的导出功能.最后决定用Apache POI来完毕该项功能.本文就项目实现过程中的一些思路与代码与大家共享.同一时候.也作为自 ...

  2. Java 使用Apache POI读取和写入Excel表格

    1,引入所用的包 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxm ...

  3. java使用org.apache.poi读取与保存EXCEL文件

    一.读EXCEL文件 package com.ruijie.wis.cloud.utils; import java.io.FileInputStream; import java.io.FileNo ...

  4. Java中使用POI读取大的Excel文件或者输入流时发生out of memory异常参考解决方案

    注意:此参考解决方案只是针对xlsx格式的excel文件! 背景 前一段时间遇到一种情况,服务器经常宕机,而且没有规律性,查看GC日志发生了out of memory,是堆溢出导致的,分析了一下堆的d ...

  5. Java下使用Apache POI生成具有三级联动下拉列表的Excel文档

    使用Apache POI生成具有三级联动下拉列表的Excel文档: 具体效果图与代码如下文. 先上效果图: 开始贴代码,代码中部分测试数据不影响功能. 第一部分(核心业务处理): 此部分包含几个方面: ...

  6. 使用Java类库POI生成简易的Excel报表

    使用Java类库POI生成简易的Excel报表 1.需求 1.数据库生成报表需要转义其中字段的信息.比如 1,有效 2.无效等 2.日期格式的自数据需要转义其格式. 3.标题的格式和数据的格式需要分别 ...

  7. 使用apache POI解析Excel文件

    1. Apache POI简介 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程式对Microsoft Office格式档案读和写的功能. 2. POI结构 ...

  8. Read / Write Excel file in Java using Apache POI

    Read / Write Excel file in Java using Apache POI 2014-04-18 BY DINESH LEAVE A COMMENT About a year o ...

  9. Apache POI – Reading and Writing Excel file in Java

    来源于:https://www.mkyong.com/java/apache-poi-reading-and-writing-excel-file-in-java/ In this article, ...

随机推荐

  1. docker save 批量导出脚本

    [root@vultr home]# cat docker_sove.sh docker images > images.txtawk '{print $1}' images.txt > ...

  2. Allowing GPU memory growth

    By default, TensorFlow maps nearly all of the GPU memory of all GPUs (subject to CUDA_VISIBLE_DEVICE ...

  3. python爬虫----scrapy框架简介和基础应用

    Scrapy是一个为了爬取网站数据,提取结构性数据而编写的应用框架. 其可以应用在数据挖掘,信息处理或存储历史数据等一系列的程序中.其最初是为了页面抓取 (更确切来说, 网络抓取 )所设计的, 也可以 ...

  4. MongoDB之增删改查

    MongoDB的默认端口为:27017 show  dbs   查看所有的数据库 MySQL和MongoDB的对应关系 MySQL MongoDB DB DB 数据库 table Collection ...

  5. word2vec详解与实战

    有那么一句话 不懂word2vec,就别说自己是研究人工智能->机器学习->自然语言处理(NLP)->文本挖掘的 所以接下来我就从头至尾的详细讲解一下word2vec这个东西. 简要 ...

  6. javascript简单的选项卡

    实现一个简单的选项卡功能 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&q ...

  7. 整合使用持久层框架mybatis 使用SqlSessionTemplate模板类与使用映射接口 对比

    spring中整合使用mybatis的用法总结 一:在Spring配置Mybatis 第一步:将mybatis-spring类包添加 到项目的类库中 第二步:编写spring和持久层衔接的xml文件, ...

  8. 可变数据类型&不可变数据类型

    不同的变量在内存中有不同的存储空间,每个存储空间都有一个ID >>> a = 32 >>> id(a) # 查看ID 1571185856 >>> ...

  9. npoi设置数据有效性

    npoi设置数据有效性 public void SetDataValidate(ISheet sheet, int firstCol, int lastCol) { CellRangeAddressL ...

  10. java 知识汇总

    一.springboot cloud 1.maven 配置 parent:org.springframework.boot:sping-boot-starter-parent dependencies ...