apache poi教程

Welcome to Apache POI Tutorial. Sometimes we need to read data from Microsoft Excel Files or we need to generate reports in Excel format, mostly for Business or Finance purposes. Java doesn’t provide built-in support for working with excel files, so we need to look for open source APIs for the job. When I started the hunt for Java APIs for excel, most of the people recommended JExcel or Apache POI.

欢迎使用Apache POI教程。 有时我们需要从Microsoft Excel文件中读取数据,或者我们需要以Excel格式生成报告,主要用于商业或财务目的。 Java不提供使用excel文件的内置支持,因此我们需要为此工作寻找开源API。 当我开始搜寻excel的Java API时,大多数人都推荐JExcel或Apache POI。

After further research, I found that Apache POI is the way to go for following main reasons. There are some other reasons related to advanced features but let’s not go into that much detail.

经过进一步的研究,我发现Apache POI是行之有效的,其主要原因如下。 还有其他一些与高级功能有关的原因,但让我们不再赘述。

  • Backing of Apache foundation.Apache基础的后盾。
  • JExcel doesn’t support xlsx format whereas POI supports both xls and xlsx formats.JExcel不支持xlsx格式,而POI支持xls和xlsx格式。
  • Apache POI provides stream-based processing, that is suitable for large files and requires less memory.Apache POI提供基于流的处理,该处理适用于大文件且需要较少的内存。

Apache POI (Apache POI)

Apache POI provides excellent support for working with Microsoft Excel documents. Apache POI is able to handle both XLS and XLSX formats of spreadsheets.

Apache POI为使用Microsoft Excel文档提供了出色的支持。 Apache POI能够处理电子表格的XLS和XLSX格式。

Some important points about Apache POI API are:

关于Apache POI API的一些重要点是:

  1. Apache POI contains HSSF implementation for Excel ’97(-2007) file format i.e XLS.Apache POI包含用于Excel '97(-2007)文件格式(即XLS)的HSSF实现。
  2. Apache POI XSSF implementation should be used for Excel 2007 OOXML (.xlsx) file format.Apache POI XSSF实现应用于Excel 2007 OOXML(.xlsx)文件格式。
  3. Apache POI HSSF and XSSF API provides mechanisms to read, write or modify excel spreadsheets.Apache POI HSSF和XSSF API提供了读取,写入或修改excel电子表格的机制。
  4. Apache POI also provides SXSSF API that is an extension of XSSF to work with very large excel sheets. SXSSF API requires less memory and is suitable when working with very large spreadsheets and heap memory is limited.Apache POI还提供了SXSSF API,它是XSSF的扩展,可以与非常大的ex​​cel工作表一起使用。 SXSSF API需要较少的内存,适用于处理非常大的电子表格且堆内存受限制的情况。
  5. There are two models to choose from – event model and user model. Event model requires less memory because the excel file is read in tokens and requires processing them. User model is more object oriented and easy to use and we will use this in our examples.有两种模型可供选择-事件模型和用户模型。 事件模型需要较少的内存,因为excel文件是在令牌中读取并需要对其进行处理的。 用户模型更加面向对象并且易于使用,我们将在示例中使用它。
  6. Apache POI provides excellent support for additional excel features such as working with Formulas, creating cell styles by filling colors and borders, fonts, headers and footers, data validations, images, hyperlinks etc.Apache POI为其他excel功能提供了出色的支持,例如使用公式,通过填充颜色和边框,字体,页眉和页脚,数据验证,图像,超链接等来创建单元格样式。

Apache POI Maven依赖关系 (Apache POI Maven Dependencies)

If you are using maven, add below Apache POI dependencies.

如果使用的是maven,请在Apache POI依赖项下面添加。

<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.10-FINAL</version>
</dependency>
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.10-FINAL</version>
</dependency>

Current version of Apache POI is 3.10-FINAL. If you are having standalone java application, include jars from below image.

Apache POI的当前版本是3.10-FINAL。 如果您有独立的Java应用程序,请在图像下方添加jar。

Apache POI示例–读取Excel文件 (Apache POI Example – Read Excel File)

Let’s say we have an excel file “Sample.xlsx” with two sheets and having data like below image. We want to read the excel file and create the list of Countries. Sheet1 has some additional data, that we will ignore while parsing it.

假设我们有一个Excel文件“ Sample.xlsx”,其中包含两张纸,数据如下图所示。 我们想读取excel文件并创建国家列表。 Sheet1还有一些其他数据,我们在解析时会忽略它们。

Our Country java bean code is:

我们国家的Java bean代码是:

Country.java

Country.java

package com.journaldev.excel.read;public class Country {private String name;private String shortCode;public Country(String n, String c){this.name=n;this.shortCode=c;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getShortCode() {return shortCode;}public void setShortCode(String shortCode) {this.shortCode = shortCode;}@Overridepublic String toString(){return name + "::" + shortCode;}}

Apache POI example program to read excel file to the list of countries looks like below.

用于将excel文件读取到国家/地区列表的Apache POI示例程序如下所示。

ReadExcelFileToList.java

ReadExcelFileToList.java

package com.journaldev.excel.read;import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;public class ReadExcelFileToList {public static List<Country> readExcelData(String fileName) {List<Country> countriesList = new ArrayList<Country>();try {//Create the input stream from the xlsx/xls fileFileInputStream fis = new FileInputStream(fileName);//Create Workbook instance for xlsx/xls file input streamWorkbook workbook = null;if(fileName.toLowerCase().endsWith("xlsx")){workbook = new XSSFWorkbook(fis);}else if(fileName.toLowerCase().endsWith("xls")){workbook = new HSSFWorkbook(fis);}//Get the number of sheets in the xlsx fileint numberOfSheets = workbook.getNumberOfSheets();//loop through each of the sheetsfor(int i=0; i < numberOfSheets; i++){//Get the nth sheet from the workbookSheet sheet = workbook.getSheetAt(i);//every sheet has rows, iterate over themIterator<Row> rowIterator = sheet.iterator();while (rowIterator.hasNext()) {String name = "";String shortCode = "";//Get the row objectRow row = rowIterator.next();//Every row has columns, get the column iterator and iterate over themIterator<Cell> cellIterator = row.cellIterator();while (cellIterator.hasNext()) {//Get the Cell objectCell cell = cellIterator.next();//check the cell type and process accordinglyswitch(cell.getCellType()){case Cell.CELL_TYPE_STRING:if(shortCode.equalsIgnoreCase("")){shortCode = cell.getStringCellValue().trim();}else if(name.equalsIgnoreCase("")){//2nd columnname = cell.getStringCellValue().trim();}else{//random data, leave itSystem.out.println("Random data::"+cell.getStringCellValue());}break;case Cell.CELL_TYPE_NUMERIC:System.out.println("Random data::"+cell.getNumericCellValue());}} //end of cell iteratorCountry c = new Country(name, shortCode);countriesList.add(c);} //end of rows iterator} //end of sheets for loop//close file input streamfis.close();} catch (IOException e) {e.printStackTrace();}return countriesList;}public static void main(String args[]){List<Country> list = readExcelData("Sample.xlsx");System.out.println("Country List\n"+list);}}

The program is very easy to understand and contains following steps:

该程序非常易于理解,包含以下步骤:

  1. Create Workbook instance based on the file type. XSSFWorkbook for xlsx format and HSSFWorkbook for xls format. Notice that we could have created a wrapper class with factory pattern to get the workbook instance based on the file name.根据文件类型创建Workbook实例。 XSSFWorkbook格式的HSSFWorkbook和xls格式的HSSFWorkbook 。 请注意,我们可以使用工厂模式创建包装类,以基于文件名获取工作簿实例。
  2. Use workbook getNumberOfSheets() to get the number of sheets and then use for loop to parse each of the sheets. Get the Sheet instance using getSheetAt(int i) method.使用工作簿getNumberOfSheets()获取工作表的数量,然后使用for循环来解析每个工作表。 使用getSheetAt(int i)方法获取Sheet实例。
  3. Get Row iterator and then Cell iterator to get the Cell object. Apache POI is using iterator pattern here.获取Row迭代器,然后获取Cell迭代器以获取单元对象。 Apache POI在这里使用迭代器模式 。
  4. Use switch-case to read the type of Cell and the process it accordingly.使用开关盒来读取Cell的类型并对其进行相应处理。

Now when we run above Apache POI example program, it produces following output on console.

现在,当我们在Apache POI示例程序之上运行时,它将在控制台上产生以下输出。

Random data::1.0
Random data::2.0
Random data::3.0
Random data::4.0
Country List
[India::IND, Afghanistan::AFG, United States of America::USA, Anguilla::AIA,
Denmark ::DNK, Dominican Republic ::DOM, Algeria ::DZA, Ecuador ::ECU]

Apache POI示例–编写Excel文件 (Apache POI Example – Write Excel File)

Writing excel file in apache POI is similar to reading, except that here we first create the workbook. Then set sheets, rows and cells values and use FileOutputStream to write it to file. Let’s write a simple apache POI example where we will use list of countries from the above method to save into another file in a single sheet.

用apache POI编写excel文件与阅读类似,不同之处在于,我们首先创建工作簿。 然后设置工作表,行和单元格的值,并使用FileOutputStream将其写入文件。 让我们写一个简单的Apache POI示例,在该示例中,我们将使用上述方法中的国家/地区列表将其保存到一张纸中的另一个文件中。

WriteListToExcelFile.java

WriteListToExcelFile.java

package com.journaldev.excel.read;import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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.xssf.usermodel.XSSFWorkbook;public class WriteListToExcelFile {public static void writeCountryListToFile(String fileName, List<Country> countryList) throws Exception{Workbook workbook = null;if(fileName.endsWith("xlsx")){workbook = new XSSFWorkbook();}else if(fileName.endsWith("xls")){workbook = new HSSFWorkbook();}else{throw new Exception("invalid file name, should be xls or xlsx");}Sheet sheet = workbook.createSheet("Countries");Iterator<Country> iterator = countryList.iterator();int rowIndex = 0;while(iterator.hasNext()){Country country = iterator.next();Row row = sheet.createRow(rowIndex++);Cell cell0 = row.createCell(0);cell0.setCellValue(country.getName());Cell cell1 = row.createCell(1);cell1.setCellValue(country.getShortCode());}//lets write the excel data to file nowFileOutputStream fos = new FileOutputStream(fileName);workbook.write(fos);fos.close();System.out.println(fileName + " written successfully");}public static void main(String args[]) throws Exception{List<Country> list = ReadExcelFileToList.readExcelData("Sample.xlsx");WriteListToExcelFile.writeCountryListToFile("Countries.xls", list);}
}

When I execute above apache POI example program, the excel file generated looks like below image.

当我执行以上apache POI示例程序时,生成的excel文件如下图所示。

Apache POI示例–阅读Excel公式 (Apache POI Example – Read Excel Formula)

Sometimes we need to handle complex excel files with formulas, let’s see a simple apache POI example to read the formula of a cell with it’s value.

有时我们需要使用公式处理复杂的excel文件,让我们看一个简单的apache POI示例,以读取具有其值的单元格的公式。

ReadExcelFormula.java

ReadExcelFormula.java

package com.journaldev.excel.read;import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;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.xssf.usermodel.XSSFWorkbook;public class ReadExcelFormula {public static void readExcelFormula(String fileName) throws IOException{FileInputStream fis = new FileInputStream(fileName);//assuming xlsx fileWorkbook workbook = new XSSFWorkbook(fis);Sheet sheet = workbook.getSheetAt(0);Iterator<Row> rowIterator = sheet.iterator();while (rowIterator.hasNext()) {Row row = rowIterator.next();Iterator<Cell> cellIterator = row.cellIterator();while (cellIterator.hasNext()) {Cell cell = cellIterator.next();switch(cell.getCellType()){case Cell.CELL_TYPE_NUMERIC:System.out.println(cell.getNumericCellValue());break;case Cell.CELL_TYPE_FORMULA:System.out.println("Cell Formula="+cell.getCellFormula());System.out.println("Cell Formula Result Type="+cell.getCachedFormulaResultType());if(cell.getCachedFormulaResultType() == Cell.CELL_TYPE_NUMERIC){System.out.println("Formula Value="+cell.getNumericCellValue());}}}}}public static void main(String args[]) throws IOException {readExcelFormula("FormulaMultiply.xlsx");}
}

When we execute above apache poi example program, we get following output.

当我们执行上面的apache poi示例程序时,我们得到以下输出。

1.0
2.0
3.0
4.0
Cell Formula=A1*A2*A3*A4
Cell Formula Result Type=0
Formula Value=24.0

Apache POI示例– Excel编写公式 (Apache POI Example – Excel Write Formula)

Sometimes, we need to do some calculations and then write the cell values. We can use the excel formulas to do this calculation and that will make it more accurate because values will change if the cell values used in calculations are changed.

有时,我们需要进行一些计算,然后编写单元格值。 我们可以使用excel公式进行此计算,这将使其更加准确,因为如果更改了计算中使用的单元格值,则值将更改。

Let’s see a simple example to write excel file with formulas using apache poi api.

让我们看一个简单的示例,使用apache poi api用公式编写excel文件。

WriteExcelWithFormula.java

WriteExcelWithFormula.java

package com.journaldev.excel.read;import java.io.FileOutputStream;
import java.io.IOException;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.xssf.usermodel.XSSFWorkbook;public class WriteExcelWithFormula {public static void writeExcelWithFormula(String fileName) throws IOException{Workbook workbook = new XSSFWorkbook();Sheet sheet = workbook.createSheet("Numbers");Row row = sheet.createRow(0);row.createCell(0).setCellValue(10);row.createCell(1).setCellValue(20);row.createCell(2).setCellValue(30);//set formula cellrow.createCell(3).setCellFormula("A1*B1*C1");//lets write to fileFileOutputStream fos = new FileOutputStream(fileName);workbook.write(fos);fos.close();System.out.println(fileName + " written successfully");}public static void main(String[] args) throws IOException {writeExcelWithFormula("Formulas.xlsx");}
}

The excel file produced with above Apache POI API example program looks like below image.

上面的Apache POI API示例程序产生的excel文件如下图所示。

That’s all on Apache POI tutorial for working with excel files, look into Apache POI classes methods to learn more features of it.

Apache POI教程包含用于处理Excel文件的全部内容,请查看Apache POI类方法以了解其更多功能。

References: Apache POI Developers Guide

参考 : Apache POI开发人员指南

翻译自: https://www.journaldev.com/2562/apache-poi-tutorial

apache poi教程

apache poi教程_Apache POI教程相关推荐

  1. poi 宋体_Apache POI Word - 字体样式和对齐方式

    本章介绍如何使用Java在Word文档中应用不同的字体样式和对齐方式. 通常,字体样式包含:字体大小,类型,粗体,斜体和下划线. 对齐分为左,中,右,对齐. 字体样式 以下代码用于设置不同样式的字体: ...

  2. POI读写excel简单教程

    POI 简介 百度百科 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. 基本功能 HSSF - 提 ...

  3. easypoi教程_SpringBoot图文教程17—上手就会 RestTemplate 使用指南

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1-Spr ...

  4. mysql5 7安装教程_MySQL57安装教程

    MySQL57安装教程... --------------------------- 首先需要下载MySQL57安装包: --------------------------------------- ...

  5. TensorFlow 中文资源精选,官方网站,安装教程,入门教程,实战项目,学习路径。

    转载至:http://www.nanjixiong.com/thread-122211-1-1.html Awesome-TensorFlow-Chinese TensorFlow 中文资源全集,学习 ...

  6. Excel导入poi、导出poi

    Excel导入poi.导出poi 依赖Jar包 <!-- 处理Excel2003 --> <dependency><groupId>org.apache.poi&l ...

  7. 【POI】Java+poi生成Excel(.xlsx)折线图

    仅通过POI的话,只能实现折线图和散点图 但POI还支持Open Xml,通过这种方式可以实现很多类型的chart (https://blog.csdn.net/u011279583/article/ ...

  8. 【POI】使用POI在Excel(.xlsx)中生成chart,指定chart位置时,createAnchor方法的偏移量参数(dx1, dy1, dx2, dy2)不生效

    前提: ①目标文件类型:.xlsx ②POI版本3.17,open xml版本1.3 ③使用POI在excel中生成chart,chart的位置是通过下面这个方法来指定的: XSSFDrawing.c ...

  9. java导入poi包_Java poi怎么导入

    展开全部 本篇面向32313133353236313431303231363533e59b9ee7ad9431333264643066对象为Java的初学者,从下载必备软件到创建一个空白的POI工程, ...

最新文章

  1. 如何快速融入团队(二)
  2. 【BZOJ】1105: [POI2007]石头花园SKA
  3. Eclipse launch failed.Binary not found解决方案
  4. 解决maven创建web项目过慢的问题
  5. [IDEA 配置MYSQL数据库连接]
  6. websoc是什么可以卸载吗_函授可以考公务员吗?什么是函授?
  7. Raspbian安装Opencv3
  8. Flutter入门:如何只关闭自身页面
  9. 光纤铜缆测试安装的基础知识你都了解了吗?
  10. K8S从懵圈到熟练 - 我们为什么会删除不了集群的命名空间?
  11. 嘉年华回顾丨 樊文凯分享Oracle 数据库异构上云最佳实践
  12. 盘点那些让人上火的提问方式(论如何让交流更高效)
  13. java.net.SocketException: socket failed: EACCES (Permission denied)
  14. Eclipse创建并运行Java程序输出Hello World
  15. java程序用户权限管理,java用户管理权限
  16. 大型网站--负载均衡架构
  17. 更换NVMe SSD不用重装系统,Windows系统迁移
  18. 2020年一级计算机考试试题,2020年2016计算机一级考试考点试题
  19. 【育儿】计算宝宝的生辰八字
  20. 手把手做一个JSP入门程序(一):程序基本介绍(JSP)

热门文章

  1. 四川专利代理机构列表
  2. Interesting Finds: 2007.12.19
  3. [转载] Python一行代码实现1到100之和
  4. [转载] Python类属性、类方法和静态方法
  5. RPC 框架之 Goole protobuf
  6. 关于HashMap,HashTable,HashSet浅析
  7. [转]WINDOW进程通信的几种方式
  8. 如何使用 @ OutputCache 指令的 VaryByCustom 属性来缓存不同版本的页面(二)
  9. python--之np.any,np.a;;
  10. git 取消head的游离状态