概述

  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依赖如下:
 <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
  •   使用poi创建execl文件

     package test.hd.poi;
    
     import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Date; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellStyle;
    import org.apache.poi.ss.usermodel.ClientAnchor;
    import org.apache.poi.ss.usermodel.Comment;
    import org.apache.poi.ss.usermodel.CreationHelper;
    import org.apache.poi.ss.usermodel.DataFormat;
    import org.apache.poi.ss.usermodel.Drawing;
    import org.apache.poi.ss.usermodel.Font;
    import org.apache.poi.ss.usermodel.RichTextString;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.util.CellRangeAddress; public class CreateExcel { public static void main(String[] args) throws IOException, InterruptedException {
    Workbook[] wbs = new Workbook[] { new HSSFWorkbook(), new XSSFWorkbook() };
    for (int i = 0; i < wbs.length; i++) {
    Workbook workbook = wbs[i];
    // 得到一个POI的工具类
    CreationHelper createHelper = workbook.getCreationHelper(); // 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
    Sheet sheet = workbook.createSheet();
    // Sheet sheet = workbook.createSheet("SheetName"); // 用于格式化单元格的数据
    DataFormat format = workbook.createDataFormat(); // 设置字体
    Font font = workbook.createFont();
    font.setFontHeightInPoints((short) 20); // 字体高度
    font.setColor(Font.COLOR_RED); // 字体颜色
    font.setFontName("黑体"); // 字体
    font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 宽度
    font.setItalic(true); // 是否使用斜体
    // font.setStrikeout(true); //是否使用划线 // 设置单元格类型
    CellStyle cellStyle = workbook.createCellStyle();
    cellStyle.setFont(font);
    cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
    cellStyle.setWrapText(true); CellStyle cellStyle2 = workbook.createCellStyle();
    cellStyle2.setDataFormat(format.getFormat("#, ## 0.0")); CellStyle cellStyle3 = workbook.createCellStyle();
    cellStyle3.setDataFormat(format.getFormat("yyyy-MM-dd HH:mm:ss")); // 添加单元格注释
    // 创建Drawing对象,Drawing是所有注释的容器.
    Drawing drawing = sheet.createDrawingPatriarch();
    // ClientAnchor是附属在WorkSheet上的一个对象, 其固定在一个单元格的左上角和右下角.
    ClientAnchor anchor = createHelper.createClientAnchor();
    // 设置注释位子
    anchor.setRow1(0);
    anchor.setRow2(2);
    anchor.setCol1(0);
    anchor.setCol2(2);
    // 定义注释的大小和位置,详见文档
    Comment comment = drawing.createCellComment(anchor);
    // 设置注释内容
    RichTextString str = createHelper.createRichTextString("Hello, World!");
    comment.setString(str);
    // 设置注释作者. 当鼠标移动到单元格上是可以在状态栏中看到该内容.
    comment.setAuthor("H__D"); // 定义几行
    for (int rownum = 0; rownum < 30; rownum++) {
    // 创建行
    Row row = sheet.createRow(rownum);
    // 创建单元格
    Cell cell = row.createCell((short) 1);
    cell.setCellValue(createHelper.createRichTextString("Hello!" + rownum));// 设置单元格内容
    cell.setCellStyle(cellStyle);// 设置单元格样式
    cell.setCellType(Cell.CELL_TYPE_STRING);// 指定单元格格式:数值、公式或字符串
    cell.setCellComment(comment);// 添加注释 // 格式化数据
    Cell cell2 = row.createCell((short) 2);
    cell2.setCellValue(11111.25);
    cell2.setCellStyle(cellStyle2); Cell cell3 = row.createCell((short) 3);
    cell3.setCellValue(new Date());
    cell3.setCellStyle(cellStyle3); sheet.autoSizeColumn((short) 0); // 调整第一列宽度
    sheet.autoSizeColumn((short) 1); // 调整第二列宽度
    sheet.autoSizeColumn((short) 2); // 调整第三列宽度
    sheet.autoSizeColumn((short) 3); // 调整第四列宽度 } // 合并单元格
    sheet.addMergedRegion(new CellRangeAddress(1, // 第一行(0)
    2, // last row(0-based)
    1, // 第一列(基于0)
    2 // 最后一列(基于0)
    )); // 保存
    String filename = "C:/Users/H__D/Desktop/workbook.xls";
    if (workbook instanceof XSSFWorkbook) {
    filename = filename + "x";
    } FileOutputStream out = new FileOutputStream(filename);
    workbook.write(out);
    out.close();
    }
    } }
  • 使用poi修改execl文件
     package test.hd.poi;
    
     import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream; import org.apache.poi.EncryptedDocumentException;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory; public class UpdateExcel { public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException { InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    //InputStream inp = new FileInputStream("workbook.xlsx"); Workbook workbook = WorkbookFactory.create(inputStream);
    Sheet sheet = workbook.getSheetAt(0);
    Row row = sheet.getRow(2);
    Cell cell = row.getCell(3);
    if (cell == null)
    cell = row.createCell(3);
    cell.setCellType(Cell.CELL_TYPE_STRING);
    cell.setCellValue("a test"); // Write the output to a file
    FileOutputStream fileOut = new FileOutputStream("C:/Users/H__D/Desktop/workbook.xls");
    workbook.write(fileOut);
    fileOut.close(); } }
  • 使用poi解析excel文件
     package test.hd.poi;
    
     import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream; import org.apache.poi.EncryptedDocumentException;
    import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.DataFormatter;
    import org.apache.poi.ss.usermodel.DateUtil;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import org.apache.poi.ss.usermodel.WorkbookFactory;
    import org.apache.poi.ss.util.CellReference; import com.microsoft.schemas.office.visio.x2012.main.CellType; public class ReadExcel { public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException { InputStream inputStream = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls");
    //InputStream inp = new FileInputStream("C:/Users/H__D/Desktop/workbook.xls"); Workbook workbook = WorkbookFactory.create(inputStream);
    Sheet sheet = workbook.getSheetAt(0); DataFormatter formatter = new DataFormatter();
    for (Row row : sheet) {
    for (Cell cell : row) {
    CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
    //单元格名称
    System.out.print(cellRef.formatAsString());
    System.out.print(" - "); //通过获取单元格值并应用任何数据格式(Date,0.00,1.23e9,$ 1.23等),获取单元格中显示的文本
    String text = formatter.formatCellValue(cell);
    System.out.println(text); //获取值并自己格式化
    switch (cell.getCellType()) {
    case Cell.CELL_TYPE_STRING:// 字符串型
    System.out.println(cell.getRichStringCellValue().getString());
    break;
    case Cell.CELL_TYPE_NUMERIC:// 数值型
    if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值
    System.out.println(cell.getDateCellValue());
    } else {// 纯数字
    System.out.println(cell.getNumericCellValue());
    }
    break;
    case Cell.CELL_TYPE_BOOLEAN:// 布尔
    System.out.println(cell.getBooleanCellValue());
    break;
    case Cell.CELL_TYPE_FORMULA:// 公式型
    System.out.println(cell.getCellFormula());
    break;
    case Cell.CELL_TYPE_BLANK:// 空值
    System.out.println();
    break;
    case Cell.CELL_TYPE_ERROR: // 故障
    System.out.println();
    break;
    default:
    System.out.println();
    }
    }
    } } }

【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. 无法连接mysql,请检查mysql是否已启动及用户密码是否设置正确

    安装好后,登录后台提示 无法连接mysql,请检查mysql是否已启动及用户密码是否设置正确 检查mysql是否启动netstat -lnpt是否有3306端口? 一 有A 检查/www/wdlinu ...

  2. display:none和visibility:hidden

    display:none和visibility:hidden的区别在哪儿? “这个问题简单?”我心里头暗自得意,按耐住自己得意又紧张的小心脏,自信满满地说,“这两个声明都可以让元素隐藏,不同之处在于d ...

  3. 字符串 String 格式化 format

    String str=String.format("Hi,%s", "王力"); 保留两位数的整数: String str=String.format(&quo ...

  4. 《学习OpenCV(中文版)》

    <模式识别中文版(希)西奥多里蒂斯> <学习OpenCV(中文版)> 矩阵计算 英文版 第四版 Matrix Computations OpenCV 3.x with Pyth ...

  5. Codeforces Beta Round #55 (Div. 2)

    Codeforces Beta Round #55 (Div. 2) http://codeforces.com/contest/59 A #include<bits/stdc++.h> ...

  6. 使用BulkCopy报错 从 bcp 客户端收到一个对 colid 19 无效的列长度

    ====System.Data.SqlClient.SqlException: 从 bcp 客户端收到一个对 colid 19 无效的列长度. 从0开始数,数据库上表的第19列

  7. [leetcode]133. Clone Graph 克隆图

    题目 给定一个无向图的节点,克隆能克隆的一切 思路 1--2 | 3--5 以上图为例, node    neighbor 1         2, 3 2         1 3         1 ...

  8. 定时器NSTimer

    /** 添加定时器 */@property (nonatomic, strong) NSTimer *timer; - (void)addTimer{ // 2秒后,自己 调用nextImage方法 ...

  9. will not be exported or published. Runtime ClassNotFoundExceptions may result.

    在eclipse中加入某个jar包时,会出现Classpath entry XXX.jar will not be exported or published. Runtime ClassNotFou ...

  10. excel数据复制到html表格<textarea>中

    方案一 多行文本框接收到复制的excel值后,在文本框的chage事件中,将excel内容分割到二维数组中,然后填充到html的表格的input或textarea中. 数据格式: 单元格复制后的数据格 ...