Apache Poi 简明教程

Apache POI - Quick Guide

Apache POI - Overview

许多时候,一个软件应用程序需要生成 Microsoft Excel 文件格式的报告。有时,甚至希望一个应用程序接收 Excel 文件作为输入数据。例如,为公司财务部门开发的应用程序将需要以 Excel 形式输出所有输出。

Many a time, a software application is required to generate reports in Microsoft Excel file format. Sometimes, an application is even expected to receive Excel files as input data. For example, an application developed for the Finance department of a company will be required to generate all their outputs in Excel.

任何想要生成 MS Office 文件作为输出的 Java 编程人员都必须使用一个预定义且只读的 API 来执行此操作。

Any Java programmer who wants to produce MS Office files as output must use a predefined and read-only API to do so.

What is Apache POI?

Apache POI 是一个流行的 API,它允许编程人员使用 Java 程序创建、修改和显示 MS Office 文件。这是一个由 Apache Software Foundation 开发和分发的开放源代码库,用于使用 Java 程序设计或修改 Microsoft Office 文件。它包含类和方法,将用户输入数据或文件解码为 MS Office 文档。

Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java programs. It is an open source library developed and distributed by Apache Software Foundation to design or modify Microsoft Office files using Java program. It contains classes and methods to decode the user input data or a file into MS Office documents.

Components of Apache POI

Apache POI 包含类和方法来处理 MS Office 的所有 OLE2 复合文档。这个 API 的组件列表如下。

Apache POI contains classes and methods to work on all OLE2 Compound documents of MS Office. The list of components of this API is given below.

  1. POIFS (Poor Obfuscation Implementation File System) − This component is the basic factor of all other POI elements. It is used to read different files explicitly.

  2. HSSF (Horrible Spreadsheet Format) − It is used to read and write xls format of MS-Excel files.

  3. XSSF (XML Spreadsheet Format) − It is used for xlsx file format of MS-Excel.

  4. HPSF (Horrible Property Set Format) − It is used to extract property sets of the MS-Office files.

  5. HWPF (Horrible Word Processor Format) − It is used to read and write doc extension files of MS-Word.

  6. XWPF (XML Word Processor Format) − It is used to read and write docx extension files of MS-Word.

  7. HSLF (Horrible Slide Layout Format) − It is used for read, create, and edit PowerPoint presentations.

  8. HDGF (Horrible DiaGram Format) − It contains classes and methods for MS-Visio binary files.

  9. HPBF (Horrible PuBlisher Format) − It is used to read and write MS-Publisher files.

本教程指导你完成使用 Java 处理 Excel 文件的流程。因此,讨论仅限于 HSSF 和 XSSF 组件。

This tutorial guides you through the process of working on Excel files using Java. Therefore the discussion is confined to HSSF and XSSF components.

Note − POI 的较早版本支持 doc、xls、ppt 等二进制文件格式。从版本 3.5 起,POI 开始支持 MS-Office 的 OOXML 文件格式,如 docx、xlsx、pptx 等。

Note − Older versions of POI support binary file formats such as doc, xls, ppt, etc. Version 3.5 onwards, POI supports OOXML file formats of MS-Office such as docx, xlsx, pptx, etc.

与 Apache POI 类似,还有其他供应商提供的用于生成 Excel 文件的库。其中包括 Aspose 的 Aspose cells for Java、Commons Libraries 的 JXL 以及 Team Dev 的 Jexcel。

Like Apache POI, there are other libraries provided by various vendors for Excel file generation. These include Aspose cells for Java by Aspose, JXL by Commons Libraries, and JExcel by Team Dev.

Apache POI - Java Excel APIs

本章介绍了一些 Java Excel API 的演变及其功能。许多供应商提供了 Java Excel 相关的 API;本章中考虑了一些。

This chapter takes you through some of the flavors of Java Excel API and their features. There are many vendors who provide Java Excel related APIs; some of them are considered in this chapter.

Aspose Cells for Java

Aspose Cells for Java 是由供应商 Aspose 开发和分发的纯许可 Java Excel API。最新版本是 8.1.2,发布于 2014 年 7 月。这是一个丰富且重量级的 API(纯 Java 类和 AWT 类的组合),用于设计可以读取、写入和操作电子表格的 Excel 组件。

Aspose Cells for Java is a purely licensed Java Excel API developed and distributed by the vendor Aspose. The latest version of this API is 8.1.2, released in July 2014. It is a rich and heavy API (combination of plain Java classes and AWT classes) for designing the Excel component that can read, write, and manipulate spreadsheets.

此 API 的常见用途如下 −

The common uses of this API are as follows −

  1. Excel reporting, build dynamic Excel reports

  2. High-fidelity Excel rendering and printing

  3. Import and export data from Excel spreadsheets

  4. Generate, edit, and convert spreadsheets

JXL

JXL 是一个专为 Selenium 设计的第三方框架,支持网络浏览器上的数据驱动自动化(网络浏览器上的数据自动更新)。但是它也被用作 JExcel API 的普通支持库,因为它具有创建、读取和写入电子表格的基本功能。

JXL is a third-party framework designed for Selenium that supports data driven automation on web browsers (auto-update of data on web browsers). However it is also used as a common support library for JExcel API because it has basic features to create, read, and write spreadsheets.

基本功能如下 −

The basic features are as follows −

  1. Generate Excel files

  2. Import data from workbooks and spreadsheets

  3. Obtain the total number of rows and columns

Note − JXL 仅支持 .xls 文件格式,并且无法处理较大的数据量。

Note − JXL supports only .xls file format and it cannot handle large data volume.

JExcel

JExcel 是 Team Dev 提供的一个纯粹许可的 API。通过使用此 API,程序员能轻松使用 .xls.xlsx 格式读取、编写、显示和修改 Excel 工作簿。此 API 能轻松与 Java Swing 和 AWT 嵌入。此 API 的最新版本是 2009 年发布的 Jexcel-2.6.12。

JExcel is a purely licensed API provided by Team Dev. Using this, programmers can easily read, write, display, and modify Excel workbooks in both .xls and .xlsx formats. This API can be easily embedded with Java Swing and AWT. The latest version of this API is Jexcel-2.6.12, released in 2009.

主要功能如下:

The main features are as follows −

  1. Automate Excel application, workbooks, spreadsheets, etc

  2. Embed workbooks in a Java Swing application as ordinary Swing component

  3. Add event listeners to workbooks and spreadsheets

  4. Add event handlers to handle the behavior of workbook and spreadsheet events

  5. Add native peers to develop custom functionality

Apache POI - Environment

本教程将指导你完成在 Windows 和 Linux 系统上设置 Apache POI 的流程。Apache POI 可以在不执行任何复杂设置程序的情况下,使用几个简单的步骤轻松安装并集成到当前的 Java 环境中。在安装时需要有用户管理权限。

This chapter takes you through the process of setting up Apache POI on Windows and Linux based systems. Apache POI can be easily installed and integrated with your current Java environment following a few simple steps without any complex setup procedures. User administration is required while installation.

System Requirements

JDK

Java SE 2 JDK 1.5 or above

Memory

1 GB RAM (recommended)

Disk Space

No minimum requirement

Operating System Version

Windows XP or above, Linux

现在让我们继续进行安装 Apache POI 的步骤。

Let us now proceed with the steps to install Apache POI.

Step 1 - Verify your Java Installation

首先,你的系统中需要安装 Java 软件开发工具包 (SDK)。要验证这一点,请根据所使用的平台执行以下两个命令。

First of all, you need to have Java Software Development Kit (SDK) installed on your system. To verify this, execute any of the two commands depending on the platform you are working on.

如果 Java 安装已正确完成,则它将显示 Java 安装的当前版本和规范。以下表中给出了一个示例输出。

If the Java installation has been done properly, then it will display the current version and specification of your Java installation. A sample output is given in the following table.

Platform

Command

Sample Output

Windows

Open command console and type − >java −version

java version "11.0.11" 2021-04-20 LTS Java™ SE Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Java HotSpot™ 64-Bit Server VM 18.9 (build 11.0.11+9-LTS-194, mixed mode)

Linux

Open command terminal and type − $java −version

java version "11.0.11" 2021-04-20 LTS Open JDK Runtime Environment 18.9 (build 11.0.11+9-LTS-194) Open JDK 64-Bit Server VM (build 11.0.11+9-LTS-194, mixed mode)

  1. We assume the readers of this tutorial have Java SDK version 11.0.11 installed on their system.

  2. In case you do not have Java SDK, download its current version from https://www.oracle.com/technetwork/java/javase/downloads/index.html and have it installed.

Step 2 - Set your Java Environment

将环境变量 JAVA_HOME 设置为指向安装 Java 的计算机上的基目录位置。例如

Set the environment variable JAVA_HOME to point to the base directory location where Java is installed on your machine. For example

Sr.No.

Platform & Description

1

Windows Set JAVA_HOME to C:\ProgramFiles\java\jdk11.0.11

2

Linux Export JAVA_HOME = /usr/local/java-current

将 Java 编译器位置的完整路径附加到系统路径。

Append the full path of Java compiler location to the System Path.

Sr.No.

Platform & Description

1

Windows Append the String "C:\Program Files\Java\jdk11.0.11\bin" to the end of the system variable PATH.

2

Linux Export PATH = $PATH:$JAVA_HOME/bin/

如上所述,从命令提示符执行命令 java -version

Execute the command java -version from the command prompt as explained above.

Step 3 - Install Apache POI Library

https://poi.apache.org/download.html 下载最新版本的 Apache POI,并将其内容解压缩到一个文件夹中,然后可以将该文件夹中的所需库连接到你的 Java 程序。我们假设这些文件保存在 C 驱动器的文件夹中。

Download the latest version of Apache POI from https://poi.apache.org/download.html and unzip its contents to a folder from where the required libraries can be linked to your Java program. Let us assume the files are collected in a folder on C drive.

将必需的 jars 的完整路径添加到 CLASSPATH,如下所示。

Add the complete path of the required jars as shown below to the CLASSPATH.

Sr.No.

Platform & Description

1

Windows Append the following strings to the end of the user variable CLASSPATH − C:\poi-bin-5.1.0\poi-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-5.1.0.jar; C:\poi-bin-5.1.0\poi-ooxml-full-5.1.0.jar; C:\poi-bin-5.1.0\lib\commons-codec-1.15.jar; C:\poi-bin-5.1.0\lib\commons-collections4-4.4.jar; C:\poi-bin-5.1.0\lib\commons-io-2.11.0.jar; C:\poi-bin-5.1.0\lib\commons-math3-3.6.1.jar; C:\poi-bin-5.1.0\lib\log4j-api-2.14.1.jar; C:\poi-bin-5.1.0\lib\SparseBitSet-1.2.jar; C\poi-bin-5.1.0\ooxml-lib\commons-compress-1.21.jar C\poi-bin-5.1.0\ooxml-lib\commons-logging-1.2.jar C\poi-bin-5.1.0\ooxml-lib\curvesapi-1.06.jar C\poi-bin-5.1.0\ooxml-lib\slf4j-api-1.7.32.jar C\poi-bin-5.1.0\ooxml-lib\xmlbeans-5.0.2.jar

2

Linux Export CLASSPATH = $CLASSPATH: /usr/share/poi-bin-5.1.0/poi-5.1.0.jar.tar: /usr/share/poi-bin-5.1.0/poi-ooxml-5.1.0.tar: /usr/share/poi-bin-5.1.0/poi-ooxml-full-5.1.0.tar: /usr/share/poi-bin-5.1.0/lib/commons-codec-1.15.jar.tar: /usr/share/poi-bin-5.1.0/lib/commons-collections4-4.4.tar: /usr/share/poi-bin-5.1.0/lib/commons-io-2.11.0.tar: /usr/share/poi-bin-5.1.0/lib/commons-math3-3.6.1.tar: /usr/share/poi-bin-5.1.0/lib/log4j-api-2.14.1.tar: /usr/share/poi-bin-5.1.0/lib/SparseBitSet-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-compress-1.21.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/commons-logging-1.2.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/curvesapi-1.06.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/slf4j-api-1.7.32.tar: /usr/share/poi-bin-5.1.0/ooxml-lib/xmlbeans-5.0.2.tar:

Apache POI - Core Classes

本章将讲解 Apache POI API 下的几个类和方法,它们对于使用 Java 程序处理 Excel 文件至关重要。

This chapter explains a few classes and methods under the Apache POI API that are critical to work on Excel files using Java programs.

Workbook

这是所有创建或维护 Excel 工作簿的类的父接口。它属于 org.apache.poi.ss.usermodel 包。实现此接口的两个类如下所示 −

This is the super-interface of all classes that create or maintain Excel workbooks. It belongs to the org.apache.poi.ss.usermodel package. The two classes that implement this interface are as follows −

  1. HSSFWorkbook − This class has methods to read and write Microsoft Excel files in .xls format. It is compatible with MS-Office versions 97-2003.

  2. XSSFWorkbook − This class has methods to read and write Microsoft Excel and OpenOffice xml files in .xls or .xlsx format. It is compatible with MS-Office versions 2007 or later.

HSSFWorkbook

它是 org.apache.poi.hssf.usermodel 包下的一种高级类。它实现了 Workbook 接口,用于处理 .xls 格式的 Excel 文件。列出此类下的一些方法和构造函数。

It is a high-level class under the org.apache.poi.hssf.usermodel package. It implements the Workbook interface and is used for Excel files in .xls format. Listed below are some of the methods and constructors under this class.

Class Constructors

Sr.No.

Constructor & Description

1

HSSFWorkbook() Creates a new HSSFWorkbook object from scratch.

2

HSSFWorkbook(DirectoryNode directory, boolean preserveNodes) Creates a new HSSFWworkbook objectinside a specific directory.

3

HSSFWorkbook(DirectoryNode directory, POIFSFileSystem fs, boolean preserveNodes) Given a POIFSFileSystem object and a specific directory within it, it creates an SSFWorkbook object to read a specified workbook.

4

HSSFWorkbook(java.io.InputStream s) Creates a new HSSFWorkbook object using an input stream.

5

HSSFWorkbook(java.io.InputStream s, boolean preserveNodes) Constructs a POI file system around your input stream.

6

HSSFWorkbook(POIFSFileSystem fs) Constructs a new HSSFWorkbook object using a POIFSFileSystem object.

7

HSSFWorkbook(POIFSFileSystem fs, boolean preserveNodes) Given a POIFSFileSystem object, it creates a new HSSFWorkbook object to read a specified workbook.

这些构造函数中经常使用的参数有 −

The frequently used parameters inside these constructors are −

  1. directory − It is the POI filesystem directory to process from.

  2. fs − It is the POI filesystem that contains the workbook stream.

  3. preservenodes − This is an optional parameter that decides whether to preserve other nodes like macros. It consumes a lot of memory as it stores all the POIFileSystem in memory (if set).

Note − HSSFWorkbook 类包含许多方法;但是,它们仅与 xls 格式兼容。在本教程中,重点在于最新版本的 Excel 文件格式。因此,此处未列出 HSSFWorkbook 的类方法。如果您需要这些类方法,那么可以在 https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html. 处参考 POI-HSSFWorkbook 类 API。

Note − The HSSFWorkbook class contains a number of methods; however they are compatible with xls format only. In this tutorial, the focus is on the latest version of Excel file formats. Hence, the class methods of HSSFWorkbook are not listed here. If you require these class methods, then refer POI-HSSFWorkbook class API at https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFWorkbook.html.

XSSFWorkbook

它是一个用于表示高低级别 Excel 文件格式的类。它属于 org.apache.xssf.usemodel 包并实现了 Workbook 接口。以下是此类下的方法和构造函数。

It is a class that is used to represent both high and low level Excel file formats. It belongs to the org.apache.xssf.usemodel package and implements the Workbook interface. Listed below are the methods and constructors under this class.

Class Constructors

Sr.No.

Constructor & Description

1

XSSFWorkbook() Creates a new XSSFworkbook object from scratch.

2

XSSFWorkbook(java.io.File file) Constructs an XSSFWorkbook object from a given file.

3

XSSFWorkbook(java.io.InputStream is) Constructs an XSSFWorkbook object, by buffering the whole input stream into memory and then opening an OPCPackage object for it.

4

XSSFWorkbook(java.lang.String path) Constructs an XSSFWorkbook object given the full path of a file.

Class Methods

Sr.No.

Method & Description

1

createSheet() Creates an XSSFSheet for this workbook, adds it to the sheets, and returns the high level representation.

2

createSheet(java.lang.String sheetname) Creates a new sheet for this Workbook and returns the high level representation.

3

createFont() Creates a new font and adds it to the workbook’s font table.

4

createCellStyle() Creates a new XSSFCellStyle and adds it to the workbook’s style table.

5

createFont() Creates a new font and adds it to the workbook’s font table.

6

setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow,int endRow) Sets the print area of a given sheet as per the specified parameters.

对于此类的剩余方法,请参考完整 API 文档获取完整方法列表 − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html.

For the remaining methods of this class, refer the complete API document at − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFWorkbook.html. for the complete list of methods.

Sheet

Sheet 是 org.apache.poi.ss.usermodel 包下的一个接口,它是创建具有特定名称的高级或低级电子表格的所有类的超接口。最常见的电子表格类型是工作表,表示为单元格网格。

Sheet is an interface under the org.apache.poi.ss.usermodel package and it is a super-interface of all classes that create high or low level spreadsheets with specific names. The most common type of spreadsheet is worksheet, which is represented as a grid of cells.

HSSFSheet

这是 org.apache.poi.hssf.usermodel 包下的一个类。它可以创建 Excel 电子表格,还允许设置工作表样式和工作表数据。

This is a class under the org.apache.poi.hssf.usermodel package. It can create excel spreadsheets and it allows to format the sheet style and sheet data.

Class Constructors

Sr.No.

Constructor & Description

1

HSSFSheet(HSSFWorkbook workbook) Creates new HSSFSheet called by HSSFWorkbook to create a sheet from scratch.

2

HSSFSheet(HSSFWorkbook workbook, InternalSheet sheet) Creates an HSSFSheet representing the given sheet object.

XSSFSheet

这是一个类,它表示电子表格的高级别表示。它位于 org.apache.poi.hssf.usermodel 包中。

This is a class which represents high level representation of excel spreadsheet. It is under org.apache.poi.hssf.usermodel package.

Class Constructors

Sr.No.

Constructor & Description

1

XSSFSheet() Creates new XSSFSheet − called by XSSFWorkbook to create a sheet from scratch.

2

XSSFSheet(PackagePart part, PackageRelationship rel) Creates an XSSFSheet representing the given package part and relationship.

Class Methods

Sr.No.

Method & Description

1

addMergedRegion(CellRangeAddress region) Adds a merged region of cells (hence those cells form one).

2

autoSizeColumn(int column) Adjusts the column width to fit the contents.

3

iterator() This method is an alias for rowIterator() to allow foreach loops

4

addHyperlink(XSSFHyperlink hyperlink) Registers a hyperlink in the collection of hyperlinks on this sheet

有关此类的其余方法,请参阅以下位置的完整 API − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFSheet.html.

For the remaining methods of this class, refer the complete API at − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFSheet.html.

Row

这是一个 org.apache.poi.ss.usermodel 包下的接口。它用于对电子表格中一行的高级表示。它是 POI 库中表示行的所有类的超级接口。

This is an interface under the org.apache.poi.ss.usermodel package. It is used for high-level representation of a row of a spreadsheet. It is a super-interface of all classes that represent rows in POI library.

XSSFRow

这是一个 org.apache.poi.xssf.usermodel 包下的类。它实现了 Row 接口,因此它可以在电子表格中创建行。以下是该类下的方法和构造函数。

This is a class under the org.apache.poi.xssf.usermodel package. It implements the Row interface, therefore it can create rows in a spreadsheet. Listed below are the methods and constructors under this class.

Class Methods

Sr.No.

Method & Description

1

createCell(int columnIndex) Creates new cells within the row and returns it.

2

setHeight(short height) Sets the height in short units.

有关此类的其余方法,请遵循给定的链接 https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRow.html

For the remaining methods of this class, follow the given link https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFRow.html

Cell

这是一个 org.apache.poi.ss.usermodel 包下的接口。它是电子表格行中的单元格表示的所有类的超级接口。

This is an interface under the org.apache.poi.ss.usermodel package. It is a super-interface of all classes that represent cells in the rows of a spreadsheet.

单元格可以获取各种属性,例如空白、数字、日期、错误等。在将单元格添加到行之前,它们应该有自己的编号(从 0 开始)。

Cells can take various attributes such as blank, numeric, date, error, etc. Cells should have their own numbers (0 based) before being added to a row.

XSSFCell

这是一个 org.apache.poi.xssf.usermodel 包下的类。它实现了 Cell 接口。它是电子表格行中单元格的高级表示。

This is a class under the org.apache.poi.xssf.usermodel package. It implements the Cell interface. It is a high-level representation of cells in the rows of a spreadsheet.

Class Methods

Sr.No.

Method & Description

1

setCellStyle(CellStyle style) Sets the style for the cell.

2

setCellType(int cellType) Sets the type of cells (numeric, formula, or string).

3

setCellValue(boolean value) Sets a boolean value for the cell.

4

setCellValue(java.util.Calendar value) Sets a date value for the cell.

5

setCellValue(double value) Sets a numeric value for the cell.

6

setCellValue(java.lang.String str) Sets a string value for the cell.

7

setHyperlink(Hyperlink hyperlink) Assigns a hyperlink to this cell.

有关此类的剩余方法和字段,请访问以下链接 − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCell.html

For the remaining methods and fields of this class, visit the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCell.html

XSSFCellStyle

此类属于 org.apache.poi.xssf.usermodel 包。它将提供有关电子表格单元格中内容格式的可能信息。它还提供了修改该格式的选项。它实现了 CellStyle 接口。

This is a class under the org.apache.poi.xssf.usermodel package. It will provide possible information regarding the format of the content in a cell of a spreadsheet. It also provides options for modifying that format. It implements the CellStyle interface.

Class Constructors

Sr.No.

Constructor & Description

1

XSSFCellStyle(int cellXfId, int cellStyleXfId, StylesTable stylesSource, ThemesTable theme) Creates a cell style from the supplied parts

2

XSSFCellStyle(StylesTable stylesSource) Creates an empty cell Style

Class Methods

Sr.No

Method & Description

1

setAlignment(short align) Sets the type of horizontal alignment for the cell

2

setBorderBottom(short border) Sets the type of border for the bottom border of the cell

3

setBorderColor(XSSFCellBorder.BorderSide side, XSSFColor color) Sets the color for the selected border

4

setBorderLeft(Short border) Sets the type of border for the left border of the cell

5

setBorderRight(short border) Sets the type of border for the right border of the cell

6

setBorderTop(short border) Sets the type of border for the top border of the cell

7

setFillBackgroundColor(XSSFColor color) Sets the background fill color represented as an XSSFColor value.

8

setFillForegroundColor(XSSFColor color) Sets the foreground fill color represented as an XSSFColor value.

9

setFillPattern(short fp) Specifies the cell fill information for pattern and solid color cell fills.

10

setFont(Font font) Sets the font for this style.

11

setRotation(short rotation) Sets the degree of rotation for the text in the cell.

12

setVerticalAlignment(short align) Sets the type of vertical alignment for the cell.

有关此类中的剩余方法和字段,请通过以下链接查找 − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCellStyle.html

For the remaining methods and fields in this class, go through the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCellStyle.html

HSSFColor

这是一个属于 org.apache.poi.hssf.util 包的类。它以嵌套类的形式提供不同的颜色。通常,用它们自己的索引来表示这些嵌套类。它实现了颜色接口。

This is a class under the org.apache.poi.hssf.util package. It provides different colors as nested classes. Usually these nested classes are represented by using their own indexes. It implements the Color interface.

Nested classes

此类中的所有嵌套类均为静态类,且每个类都有自己的索引。这些嵌套颜色类用于单元格格式设置,例如单元格内容、边框、前景色和背景色。如下列出的几个嵌套类。

All nested classes of this class are static and each class has its index. These nested color classes are used for cell formatting such as cell content, border, foreground, and background. Listed below are some of the nested classes.

Sr.No.

Class names (colors)

1

HSSFColor.AQUA

2

HSSFColor.AUTOMATIC

3

HSSFColor.BLACK

4

HSSFColor.BLUE

5

HSSFColor.BRIGHT_GREEN

6

HSSFColor.BRIGHT_GRAY

7

HSSFColor.CORAL

8

HSSFColor.DARK_BLUE

9

HSSFColor.DARK_GREEN

10

HSSFColor.SKY_BLUE

11

HSSFColor.WHITE

12

HSSFColor.YELLOW

Class Methods

此类中只有一个方法非常重要,用于获取索引值。

Only one method of this class is important and that is used to get the index value.

Sr.No.

Method & Description

1

getIndex() This method is used to get the index value of a nested class.

有关剩余方法和嵌套类,请参考以下链接 − https://poi.apache.org/apidocs/org/apache/poi/hssf/util/HSSFColor.html

For the remaining methods and nested classes, refer the following link − https://poi.apache.org/apidocs/org/apache/poi/hssf/util/HSSFColor.html

XSSFColor

这是一个属于 org.apache.poi.xssf.usermodel 包的类。它用于在电子表格中表示颜色。它实现了颜色接口。如下列出它的几个方法和构造函数。

This is a class under the org.apache.poi.xssf.usermodel package. It is used to represent color in a spreadsheet. It implements the Color interface. Listed below are some of its methods and constructors.

Class Constructors

Sr.No.

Constructor & Description

1

XSSFColor() Creates a new instance of XSSFColor.

2

XSSFColor(byte[] rgb) Creates a new instance of XSSFColor using RGB.

3

XSSFColor(java.awt.Color clr) Creates a new instance of XSSFColor using the Color class from the awt package.

Class Methods

Sr.No.

Method & Description

1

setAuto(boolean auto) Sets a boolean value to indicate that the ctColor is automatic and the system ctColor is dependent.

2

setIndexed(int indexed) Sets indexed ctColor value as system ctColor.

For the remaining methods, visit the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFColor.html

XSSFFont

这是一个属于 org.apache.poi.xssf.usermodel 包的类。它实现了字体接口,因此它可以在工作簿中处理不同的字体。

This is a class under the org.apache.poi.xssf.usermodel package. It implements the Font interface and therefore it can handle different fonts in a workbook.

Class Constructor

Sr.No.

Constructor & Description

1

XSSFFont() Creates a new XSSFont instance.

Class Methods

Sr.No.

Method & Description

1

setBold(boolean bold) Sets a Boolean value for the 'bold' attribute.

2

setColor(short color) Sets the indexed color for the font.

3

setColor(XSSFColor color) Sets the color for the font in Standard Alpha RGB color value.

4

setFontHeight(short height) Sets the font height in points.

5

setFontName(java.lang.String name) Sets the name for the font.

6

setItalic(boolean italic) Sets a Boolean value for the 'italic' property.

对于其余方法,请通过以下链接进行 − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFFont.html

For the remaining methods, go through the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFFont.html

这是一个 org.apache.poi.xssf.usermodel 包下的类。它实现了 Hyperlink 接口。它用于设置指向电子表格中单元格内容的超链接。

This is a class under the org.apache.poi.xssf.usermodel package. It implements the Hyperlink interface. It is used to set a hyperlink to the cell contents of a spreadsheet.

Class Methods

Sr.No.

Method & Description

1

setAddress(java.lang.String address) Hyperlink address.

For the remaining methods, visit the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFHyperlink.html

XSSFCreationHelper

这是一个 org.apache.poi.xssf.usermodel 包下的类。它实现了 CreationHelper 接口。它用作公式评估和设置超链接的支持类。

This is a class under the org.apache.poi.xssf.usermodel package. It implements the CreationHelper interface. It is used as a support class for formula evaluation and setting up hyperlinks.

Class Methods

Sr.No.

Method & Description

1

createFormulaEvaluator() Creates an XSSFFormulaEvaluator instance, the object that evaluates formula cells.

2

createHyperlink(int type) Creates a new XSSFHyperlink.

For the remaining methods, refer the following link − https://poi.apache.org/apidocs/org/apache/poi/xssf/usermodel/XSSFCreationHelper.html

XSSFPrintSetup

这是一个 org.apache.poi.xsssf.usermodel 包下的类。它实现了 PrintSetup 接口。它用于设置打印页面大小、区域、选项和设置。

This is a class under the org.apache.poi.xsssf.usermodel package. It implements the PrintSetup interface. It is used to set print page size, area, options, and settings.

Class Methods

Sr.No.

Method & Description

1

setLandscape(boolean ls) Sets a boolean value to allow or block landscape printing.

2

setLeftToRight(boolean ltor) Sets whether to go left to right or top down in ordering while printing.

3

setPaperSize(short size) Sets the paper size.

For the remaining methods, visit the following link − https://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/HSSFPrintSetup.html

Apache POI - Workbooks

这里的术语“工作簿”意味着 Microsoft Excel 文件。完成本章后,您将可以用 Java 程序创建新工作簿并打开现有工作簿。

Here the term 'Workbook' means Microsoft Excel file. After completion of this chapter, you will be able to create new Workbooks and open existing Workbooks with your Java program.

Create Blank Workbook

以下简单程序用于创建一个空白 Microsoft Excel 工作簿。

The following simple program is used to create a blank Microsoft Excel Workbook.

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class CreateWorkBook {
   public static void main(String[] args)throws Exception {
      //Create Blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Create file system using specific name
      FileOutputStream out = new FileOutputStream(new File("createworkbook.xlsx"));

      //write operation workbook using file out object
      workbook.write(out);
      out.close();
      System.out.println("createworkbook.xlsx written successfully");
   }
}

让我们将上面的 Java 代码保存为 CreateWorkBook.java ,然后按照以下步骤从命令提示符处进行编译和执行 -

Let us save the above Java code as CreateWorkBook.java, and then compile and execute it from the command prompt as follows −

$javac CreateWorkBook.java
$java CreateWorkBook

如果您的系统环境配置了 POI 库,它将编译和执行以在您当前的目录中生成名为 createworkbook.xlsx 的空白 Excel 文件,并在命令提示符中显示以下输出。

If your system environment is configured with the POI library, it will compile and execute to generate the blank Excel file named createworkbook.xlsx in your current directory and display the following output in the command prompt.

createworkbook.xlsx written successfully

Open Existing Workbook

使用以下代码打开现有的工作簿。

Use the following code to open an existing workbook.

import java.io.*;
import org.apache.poi.xssf.usermodel.*;

public class OpenWorkBook {
   public static void main(String args[])throws Exception {
	   try {
         File file = new File("openworkbook.xlsx");
         FileInputStream fIP = new FileInputStream(file);

         //Get the workbook instance for XLSX file
         XSSFWorkbook workbook = new XSSFWorkbook(fIP);

         if(file.isFile() && file.exists()) {
            System.out.println("openworkbook.xlsx file open successfully.");
         } else {
            System.out.println("Error to open openworkbook.xlsx file.");
         }
      } catch(Exception e) {
         System.out.println("Error to open openworkbook.xlsx file." + e.getMessage());
      }
   }
}

将上述 Java 代码保存为 OpenWorkBook.java 然后从命令提示符编译并执行它,如下所示−

Save the above Java code as OpenWorkBook.java, and then compile and execute it from the command prompt as follows −

$javac OpenWorkBook.java
$java OpenWorkBook

它会编译并执行以生成以下输出。

It will compile and execute to generate the following output.

openworkbook.xlsx file open successfully.

打开工作簿后,您可以在其上执行读取和写入操作。

After opening a workbook, you can perform read and write operations on it.

Apache POI - Spreadsheets

本章介绍了如何创建电子表格以及使用 Java 操纵它。电子表格是 Excel 文件中的一页;它包含具有特定名称的行和列。

This chapter explains how to create a spreadsheet and manipulate it using Java. Spreadsheet is a page in an Excel file; it contains rows and columns with specific names.

完成本章学习后,您将能够创建电子表格并对其执行读取操作。

After completing this chapter, you will be able to create a spreadsheet and perform read operations on it.

Create a Spreadsheet

首先,我们使用前面章节中讨论的引用类创建电子表格。按照上一章节,首先创建一个工作簿,然后再创建一张工作表。

First of all, let us create a spreadsheet using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a workbook first and then we can go on and create a sheet.

以下代码片段用于创建电子表格。

The following code snippet is used to create a spreadsheet.

//Create Blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();

//Create a blank spreadsheet
XSSFSheet spreadsheet = workbook.createSheet("Sheet Name");

Rows on Spreadsheet

电子表格具有网格布局。行和列使用特定名称进行标识。列使用字母标识,行使用数字标识。

Spreadsheets have a grid layout. The rows and columns are identified with specific names. The columns are identified with alphabets and rows with numbers.

以下代码片段用于创建行。

The following code snippet is used to create a row.

XSSFRow row = spreadsheet.createRow((short)1);

Write into a Spreadsheet

让我们考虑一个员工数据示例。此处,员工数据采用表格形式给出。

Let us consider an example of employee data. Here the employee data is given in a tabular form.

Emp Id

Emp Name

Designation

Tp01

Gopal

Technical Manager

TP02

Manisha

Proof Reader

Tp03

Masthan

Technical Writer

Tp04

Satish

Technical Writer

Tp05

Krishna

Technical Writer

以下代码用于将上述数据写入电子表格。

The following code is used to write the above data into a spreadsheet.

import java.io.File;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Writesheet {
   public static void main(String[] args) throws Exception {
      //Create blank workbook
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Create a blank sheet
      XSSFSheet spreadsheet = workbook.createSheet(" Employee Info ");

      //Create row object
      XSSFRow row;

      //This data needs to be written (Object[])
      Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
      empinfo.put( "1", new Object[] { "EMP ID", "EMP NAME", "DESIGNATION" });
      empinfo.put( "2", new Object[] { "tp01", "Gopal", "Technical Manager" });
      empinfo.put( "3", new Object[] { "tp02", "Manisha", "Proof Reader" });
      empinfo.put( "4", new Object[] { "tp03", "Masthan", "Technical Writer" });
      empinfo.put( "5", new Object[] { "tp04", "Satish", "Technical Writer" });
      empinfo.put( "6", new Object[] { "tp05", "Krishna", "Technical Writer" });

      //Iterate over data and write to sheet
      Set < String > keyid = empinfo.keySet();
      int rowid = 0;

      for (String key : keyid) {
         row = spreadsheet.createRow(rowid++);
         Object [] objectArr = empinfo.get(key);
         int cellid = 0;

         for (Object obj : objectArr) {
            Cell cell = row.createCell(cellid++);
            cell.setCellValue((String)obj);
         }
      }
      //Write the workbook in file system
      FileOutputStream out = new FileOutputStream(new File("Writesheet.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("Writesheet.xlsx written successfully");
   }
}

将上述 Java 代码保存为 Writesheet.java ,然后在命令提示符中将其编译并运行,如下所示:

Save the above Java code as Writesheet.java, and then compile and run it from the command prompt as follows −

$javac Writesheet.java
$java Writesheet

它将编译和执行以在当前目录中生成一个名为 Writesheet.xlsx 的 Excel 文件,您将在命令提示符中获得以下输出。

It will compile and execute to generate an Excel file named Writesheet.xlsx in your current directory and you will get the following output in the command prompt.

Writesheet.xlsx written successfully

Writesheet.xlsx 文件如下所示:

The Writesheet.xlsx file looks as follows −

writesheet

Read from a Spreadsheet

让我们将上述名为 Writesheet.xslx 的 Excel 文件视为输入。观察以下代码;它用于读取电子表格中的数据。

Let us consider the above excel file named Writesheet.xslx as input. Observe the following code; it is used for reading the data from a spreadsheet.

import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Readsheet {
   static XSSFRow row;
   public static void main(String[] args) throws Exception {
      FileInputStream fis = new FileInputStream(new File("WriteSheet.xlsx"));
      XSSFWorkbook workbook = new XSSFWorkbook(fis);
      XSSFSheet spreadsheet = workbook.getSheetAt(0);
      Iterator < Row >  rowIterator = spreadsheet.iterator();

      while (rowIterator.hasNext()) {
         row = (XSSFRow) rowIterator.next();
         Iterator < Cell >  cellIterator = row.cellIterator();

         while ( cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            switch (cell.getCellType()) {
               case NUMERIC:
                  System.out.print(cell.getNumericCellValue() + " \t\t ");
                  break;

               case STRING:
                  System.out.print(
                  cell.getStringCellValue() + " \t\t ");
                  break;
            }
         }
         System.out.println();
      }
      fis.close();
   }
}

让我们将上述代码保存在 Readsheet.java 文件中,然后在命令提示符中将其编译并运行,如下所示:

Let us keep the above code in Readsheet.java file, and then compile and run it from the command prompt as follows −

$javac Readsheet.java
$java Readsheet

如果系统环境配置了 POI 库,它将编译和执行以在命令提示符中生成以下输出。

If your system environment is configured with the POI library, it will compile and execute to generate the following output in the command prompt.

EMP ID   EMP NAME       DESIGNATION
 tp01     Gopal       Technical Manager
 tp02     Manisha     Proof Reader
 tp03     Masthan     Technical Writer
 tp04     Satish      Technical Writer
 tp05     Krishna     Technical Writer

Apache POI - Cells

您输入到电子表格中的任何数据始终存储在单元格中。我们使用行和列的标签来标识单元格。本章介绍如何使用 Java 编程操纵电子表格中单元格中的数据。

Any data that you enter into a spreadsheet is always stored in a cell. We use the labels of rows and columns to identify a cell. This chapter describes how to manipulate data in cells in a spreadsheet using Java programming.

Create a Cell

创建单元格之前,您需要创建一行。行只不过是一组单元格。

You need to create a row before creating a cell. A row is nothing but a collection of cells.

以下代码段用于创建单元格。

The following code snippet is used for creating a cell.

//create new workbook
XSSFWorkbook workbook = new XSSFWorkbook();

//create spreadsheet with a name
XSSFSheet spreadsheet = workbook.createSheet("new sheet");

//create first row on a created spreadsheet
XSSFRow row = spreadsheet.createRow(0);

//create first cell on created row
XSSFCell cell = row.createCell(0);

Types of Cells

单元格类型指定单元格可以包含字符串、数值或公式。字符串单元格不能容纳数值,数值单元格不能容纳字符串。

The cell type specifies whether a cell can contain strings, numeric value, or formulas. A string cell cannot hold numeric values and a numeric cell cannot hold strings.

以下代码用于在电子表格中创建不同类型的单元格。

The following code is used to create different types of cells in a spreadsheet.

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TypesofCells {
   public static void main(String[] args)throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("cell types");

      XSSFRow row = spreadsheet.createRow((short) 2);
      row.createCell(0).setCellValue("Type of Cell");
      row.createCell(1).setCellValue("cell value");

      row = spreadsheet.createRow((short) 3);
      row.createCell(0).setCellValue("set cell type BLANK");
      row.createCell(1);

      row = spreadsheet.createRow((short) 4);
      row.createCell(0).setCellValue("set cell type BOOLEAN");
      row.createCell(1).setCellValue(true);

      row = spreadsheet.createRow((short) 5);
      row.createCell(0).setCellValue("set cell type date");
      row.createCell(1).setCellValue(new Date());

      row = spreadsheet.createRow((short) 6);
      row.createCell(0).setCellValue("set cell type numeric");
      row.createCell(1).setCellValue(20 );

      row = spreadsheet.createRow((short) 7);
      row.createCell(0).setCellValue("set cell type string");
      row.createCell(1).setCellValue("A String");

      FileOutputStream out = new FileOutputStream(new File("typesofcells.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("typesofcells.xlsx written successfully");
   }
}

将以上代码保存在名为 TypesofCells.java 的文件中,从命令提示符编译并执行代码,如下所示:

Save the above code in a file named TypesofCells.java, compile and execute it from the command prompt as follows −

$javac TypesofCells.java
$java TypesofCells

如果你的系统配置有 POI 库,那么你可以在当前目录中编译并执行代码,生成一个名为 typesofcells.xlsx 的 Excel 文件,然后显示以下输出。

If your system is configured with the POI library, then it will compile and execute to generate an Excel file named typesofcells.xlsx in your current directory and display the following output.

typesofcells.xlsx written successfully

typesofcells.xlsx 文件如下所示:

The typesofcells.xlsx file looks as follows −

typesofcells

Cell Styles

在这里,你可以学习如何进行单元格格式化,并应用不同的样式,如合并相邻单元格、添加边框、设置单元格对齐和填充颜色。

Here you can learn how to do cell formatting and apply different styles such as merging adjacent cells, adding borders, setting cell alignment and filling with colors.

以下代码用于使用 Java 编程对单元格应用不同的样式。

The following code is used to apply different styles to cells using Java programming.

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Color;
import org.apache.poi.ss.usermodel.FillPatternType;

public class CellStyle {
   public static void main(String[] args)throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("cellstyle");
      XSSFRow row = spreadsheet.createRow((short) 1);
      row.setHeight((short) 800);
      XSSFCell cell = (XSSFCell) row.createCell((short) 1);
      cell.setCellValue("test of merging");

      //MEARGING CELLS
      //this statement for merging cells

      spreadsheet.addMergedRegion(
         new CellRangeAddress(
            1, //first row (0-based)
            1, //last row (0-based)
            1, //first column (0-based)
            4 //last column (0-based)
         )
      );

      //CELL Alignment
      row = spreadsheet.createRow(5);
      cell = (XSSFCell) row.createCell(0);
      row.setHeight((short) 800);

      // Top Left alignment
      XSSFCellStyle style1 = workbook.createCellStyle();
      spreadsheet.setColumnWidth(0, 8000);
      style1.setAlignment(HorizontalAlignment.LEFT);
      style1.setVerticalAlignment(VerticalAlignment.TOP);
      cell.setCellValue("Top Left");
      cell.setCellStyle(style1);
      row = spreadsheet.createRow(6);
      cell = (XSSFCell) row.createCell(1);
      row.setHeight((short) 800);

      // Center Align Cell Contents
      XSSFCellStyle style2 = workbook.createCellStyle();
      style2.setAlignment(HorizontalAlignment.CENTER);
      style2.setVerticalAlignment(VerticalAlignment.CENTER);
      cell.setCellValue("Center Aligned");
      cell.setCellStyle(style2);
      row = spreadsheet.createRow(7);
      cell = (XSSFCell) row.createCell(2);
      row.setHeight((short) 800);

      // Bottom Right alignment
      XSSFCellStyle style3 = workbook.createCellStyle();
      style3.setAlignment(HorizontalAlignment.RIGHT);
      style3.setVerticalAlignment(VerticalAlignment.BOTTOM);
      cell.setCellValue("Bottom Right");
      cell.setCellStyle(style3);
      row = spreadsheet.createRow(8);
      cell = (XSSFCell) row.createCell(3);

      // Justified Alignment
      XSSFCellStyle style4 = workbook.createCellStyle();
      style4.setAlignment(HorizontalAlignment.JUSTIFY);
      style4.setVerticalAlignment(VerticalAlignment.JUSTIFY);
      cell.setCellValue("Contents are Justified in Alignment");
      cell.setCellStyle(style4);

      //CELL BORDER
      row = spreadsheet.createRow((short) 10);
      row.setHeight((short) 800);
      cell = (XSSFCell) row.createCell((short) 1);
      cell.setCellValue("BORDER");

      XSSFCellStyle style5 = workbook.createCellStyle();
      style5.setBorderBottom(BorderStyle.THICK);
      style5.setBottomBorderColor(IndexedColors.BLUE.getIndex());
      style5.setBorderLeft(BorderStyle.DOUBLE);
      style5.setLeftBorderColor(IndexedColors.GREEN.getIndex());
      style5.setBorderRight(BorderStyle.HAIR);
      style5.setRightBorderColor(IndexedColors.RED.getIndex());
      style5.setBorderTop(BorderStyle.DOTTED);
      style5.setTopBorderColor(IndexedColors.CORAL.getIndex());
      cell.setCellStyle(style5);

      //Fill Colors
      //background color
      row = spreadsheet.createRow((short) 10 );
      cell = (XSSFCell) row.createCell((short) 1);

      XSSFCellStyle style6 = workbook.createCellStyle();
      style6.setFillBackgroundColor(IndexedColors.LIME.index);
      style6.setFillPattern(FillPatternType.LESS_DOTS);
      style6.setAlignment(HorizontalAlignment.FILL);
      spreadsheet.setColumnWidth(1,8000);
      cell.setCellValue("FILL BACKGROUNG/FILL PATTERN");
      cell.setCellStyle(style6);

      //Foreground color
      row = spreadsheet.createRow((short) 12);
      cell = (XSSFCell) row.createCell((short) 1);

      XSSFCellStyle style7 = workbook.createCellStyle();
      style7.setFillForegroundColor(IndexedColors.BLUE.index);
      style7.setFillPattern( FillPatternType.LESS_DOTS);
      style7.setAlignment(HorizontalAlignment.FILL);
      cell.setCellValue("FILL FOREGROUND/FILL PATTERN");
      cell.setCellStyle(style7);

      FileOutputStream out = new FileOutputStream(new File("cellstyle.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("cellstyle.xlsx written successfully");
   }
}

将以上代码保存在名为 CellStyle.java 的文件中,从命令提示符编译并执行代码,如下所示:

Save the above code in a file named CellStyle.java, compile and execute it from the command prompt as follows −

$javac CellStyle.java
$java CellStyle

它将在你的当前目录中生成一个名为 cellstyle.xlsx 的 Excel 文件,然后显示以下输出。

It will generate an Excel file named cellstyle.xlsx in your current directory and display the following output.

cellstyle.xlsx written successfully

Apache POI - Fonts

本章介绍如何在 Excel 电子表格中设置不同的字体、应用样式和在不同的角度方向显示文本。

This chapter explains how to set different fonts, apply styles, and display text in different angles of direction in an Excel spreadsheet.

每个系统都捆绑了大量的字体,如 Arial、Impact、Times New Roman 等。如果需要,还可以使用新字体更新此集合。类似地,可以显示字体的各种样式,例如粗体、斜体、下划线、删除线等。

Every system comes bundled with a huge collection of fonts such as Arial, Impact, Times New Roman, etc. The collection can also be updated with new fonts, if required. Similarly there are various styles in which a font can be displayed, for example, bold, italic, underline, strike through, etc.

Fonts and Font Styles

以下代码用于将特定的字体和样式应用于单元格的内容。

The following code is used to apply a particular font and style to the contents of a cell.

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.hssf.util.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class FontStyle {
   public static void main(String[] args)throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("Fontstyle");
      XSSFRow row = spreadsheet.createRow(2);

      //Create a new font and alter it.
      XSSFFont font = workbook.createFont();
      font.setFontHeightInPoints((short) 30);
      font.setFontName("IMPACT");
      font.setItalic(true);
      font.setColor(IndexedColors.BRIGHT_GREEN.index);

      //Set font into style
      XSSFCellStyle style = workbook.createCellStyle();
      style.setFont(font);

      // Create a cell with a value and set style to it.
      XSSFCell cell = row.createCell(1);
      cell.setCellValue("Font Style");
      cell.setCellStyle(style);

      FileOutputStream out = new FileOutputStream(new File("fontstyle.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("fontstyle.xlsx written successfully");
   }
}

让我们将上述代码保存在名为 FontStyle.java 的文件中。从命令提示符编译并执行它,如下所示−

Let us save the above code in a file named FontStyle.java. Compile and execute it from the command prompt as follows −

$javac FontStyle.java
$java FontStyle

它会在您的当前目录中生成一个名为 fontstyle.xlsx 的 Excel 文件,并显示命令提示符上的以下输出。

It generates an Excel file named fontstyle.xlsx in your current directory and display the following output on the command prompt.

fontstyle.xlsx written successfully

fontstyle.xlsx 文件如下所示−

The fontstyle.xlsx file looks as follows −

fontstyle

Text Direction

在这里,您可以了解如何在不同的角度设置文本方向。通常,单元格内容从左到右水平显示,角度为 00;但是,如果需要,可以使用以下代码旋转文本方向。

Here you can learn how to set the text direction in different angles. Usually cell contents are displayed horizontally, from left to right, and at 00 angle; however you can use the following code to rotate the text direction, if required.

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TextDirection {
   public static void main(String[] args)throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("Text direction");
      XSSFRow row = spreadsheet.createRow(2);
      XSSFCellStyle myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 0);
      XSSFCell cell = row.createCell(1);
      cell.setCellValue("0D angle");
      cell.setCellStyle(myStyle);

      //30 degrees
      myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 30);
      cell = row.createCell(3);
      cell.setCellValue("30D angle");
      cell.setCellStyle(myStyle);

      //90 degrees
      myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 90);
      cell = row.createCell(5);
      cell.setCellValue("90D angle");
      cell.setCellStyle(myStyle);

      //120 degrees
      myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 120);
      cell = row.createCell(7);
      cell.setCellValue("120D angle");
      cell.setCellStyle(myStyle);

      //270 degrees
      myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 270);
      cell = row.createCell(9);
      cell.setCellValue("270D angle");
      cell.setCellStyle(myStyle);

      //360 degrees
      myStyle = workbook.createCellStyle();
      myStyle.setRotation((short) 360);
      cell = row.createCell(12);
      cell.setCellValue("360D angle");
      cell.setCellStyle(myStyle);

      FileOutputStream out = new FileOutputStream(new File("textdirection.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("textdirection.xlsx written successfully");
   }
}

将上述代码保留在 TextDirectin.java 文件中,然后从命令提示符编译并执行它,如下所示−

Keep the above code in TextDirectin.java file, then compile and execute it from the command prompt as follows −

$javac TextDirection.java
$java TextDirection

它会编译并执行以生成在您当前目录中名为 textdirection.xlsx 的 Excel 文件,并在命令提示符上显示以下输出。

It will compile and execute to generate an Excel file named textdirection.xlsx in your current directory and display the following output on the command prompt.

textdirection.xlsx written successfully

textdirection.xlsx 文件如下所示−

The textdirection.xlsx file looks as follows −

textdirection

Apache POI - Formula

本章将引导您了解使用 Java 编程在单元格上应用不同的公式。Excel 应用程序的基本目的是通过在其上应用公式来维护数字数据。

This chapter takes you through the process of applying different formulas on cells using Java programming. The basic purpose of Excel application is to maintain numerical data by applying formulas on it.

在公式中,我们传递 Excel 表中值动态值或位置。在执行此公式后,您将获得所需的结果。下表列出了 Excel 中经常使用的一些基本公式。

In a formula, we pass dynamic values or locations of the values in the Excel sheet. On executing this formula, you get the desired result. The following table lists a few basic formulas that are frequently used in Excel.

Operation

Syntax

Adding multiple numbers

= SUM(Loc1:Locn) or = SUM(n1,n2,)

Count

= COUNT(Loc1:Locn) or = COUNT(n1,n2,)

Power of two numbers

= POWER(Loc1,Loc2) or = POWER(number, power)

Max of multiple numbers

= MAX(Loc1:Locn) or = MAX(n1,n2,)

Product

= PRODUCT(Loc1:Locn) or = PRODUCT(n1,n2,)

Factorial

= FACT(Locn) or = FACT(number)

Absolute number

= ABS(Locn) or = ABS(number)

Today date

=TODAY()

Converts lowercase

= LOWER(Locn) or = LOWER(text)

Square root

= SQRT(locn) or = SQRT(number)

以下代码用来给单元格添加公式并执行它。

The following code is used to add formulas to a cell and execute it.

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class Formula {
   public static void main(String[] args)throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("formula");
      XSSFRow row = spreadsheet.createRow(1);
      XSSFCell cell = row.createCell(1);

      cell.setCellValue("A = ");
      cell = row.createCell(2);
      cell.setCellValue(2);
      row = spreadsheet.createRow(2);
      cell = row.createCell(1);
      cell.setCellValue("B = ");
      cell = row.createCell(2);
      cell.setCellValue(4);
      row = spreadsheet.createRow(3);
      cell = row.createCell(1);
      cell.setCellValue("Total = ");
      cell = row.createCell(2);

      // Create SUM formula
      cell.setCellFormula("SUM(C2:C3)");
      cell = row.createCell(3);
      cell.setCellValue("SUM(C2:C3)");
      row = spreadsheet.createRow(4);
      cell = row.createCell(1);
      cell.setCellValue("POWER =");
      cell=row.createCell(2);

      // Create POWER formula
      cell.setCellFormula("POWER(C2,C3)");
      cell = row.createCell(3);
      cell.setCellValue("POWER(C2,C3)");
      row = spreadsheet.createRow(5);
      cell = row.createCell(1);
      cell.setCellValue("MAX = ");
      cell = row.createCell(2);

      // Create MAX formula
      cell.setCellFormula("MAX(C2,C3)");
      cell = row.createCell(3);
      cell.setCellValue("MAX(C2,C3)");
      row = spreadsheet.createRow(6);
      cell = row.createCell(1);
      cell.setCellValue("FACT = ");
      cell = row.createCell(2);

      // Create FACT formula
      cell.setCellFormula("FACT(C3)");
      cell = row.createCell(3);
      cell.setCellValue("FACT(C3)");
      row = spreadsheet.createRow(7);
      cell = row.createCell(1);
      cell.setCellValue("SQRT = ");
      cell = row.createCell(2);

      // Create SQRT formula
      cell.setCellFormula("SQRT(C5)");
      cell = row.createCell(3);
      cell.setCellValue("SQRT(C5)");
      workbook.getCreationHelper().createFormulaEvaluator().evaluateAll();
      FileOutputStream out = new FileOutputStream(new File("formula.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("fromula.xlsx written successfully");
   }
}

将以上代码保存在 Formula.java 中,然后从命令行处编译并执行它,如下所示 −

Save the above code as Formula.java and then compile and execute it from the command prompt as follows −

$javac Formula.java
$java Formula

它将在你的当前目录中生成名为 formula.xlsx 的 Excel 文件,并在命令行中显示以下输出。

It will generate an Excel file named formula.xlsx in your current directory and display the following output on the command prompt.

fromula.xlsx written successfully

formula.xlsx 文件如下: −

The formula.xlsx file looks as follows −

formula

本章解释了如何向单元格中的内容添加超链接。通常使用超链接来访问任意网页 URL、电子邮件或外部文件。

This chapter explains how to add hyperlinks to the contents in a cell. Usually hyperlinks are used to access any web URL, email, or an external file.

以下代码展示了如何创建单元格上的超链接。

The following code shows how to create hyperlinks on cells.

import java.io.File;
import java.io.FileOutputStream;

import org.apache.poi.common.usermodel.Hyperlink;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFHyperlink;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class HyperlinkEX {
   public static void main(String[] args) throws Exception {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook.createSheet("Hyperlinks");
      XSSFCell cell;
      CreationHelper createHelper = workbook.getCreationHelper();
      XSSFCellStyle hlinkstyle = workbook.createCellStyle();
      XSSFFont hlinkfont = workbook.createFont();
      hlinkfont.setUnderline(XSSFFont.U_SINGLE);
      hlinkfont.setColor(IndexedColors.BLUE.index);
      hlinkstyle.setFont(hlinkfont);

      //URL Link
      cell = spreadsheet.createRow(1).createCell((short) 1);
      cell.setCellValue("URL Link");
      XSSFHyperlink link = (XSSFHyperlink)createHelper.createHyperlink(HyperlinkType.URL);
      link.setAddress("https://www.tutorialspoint.com/");
      cell.setHyperlink((XSSFHyperlink) link);
      cell.setCellStyle(hlinkstyle);

      //Hyperlink to a file in the current directory
      cell = spreadsheet.createRow(2).createCell((short) 1);
      cell.setCellValue("File Link");
      link = (XSSFHyperlink)createHelper.createHyperlink(HyperlinkType.FILE);
      link.setAddress("cellstyle.xlsx");
      cell.setHyperlink(link);
      cell.setCellStyle(hlinkstyle);

      //e-mail link
      cell = spreadsheet.createRow(3).createCell((short) 1);
      cell.setCellValue("Email Link");
      link = (XSSFHyperlink)createHelper.createHyperlink(HyperlinkType.EMAIL);
      link.setAddress("mailto:contact@tutorialspoint.com?" + "subject = Hyperlink");
      cell.setHyperlink(link);
      cell.setCellStyle(hlinkstyle);

      FileOutputStream out = new FileOutputStream(new File("hyperlink.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("hyperlink.xlsx written successfully");
   }
}

将上述代码保存为 HyperlinkEX.java 。从命令提示符按照如下方式进行编译并执行 −

Save the above code as HyperlinkEX.java. Compile and execute it from the command prompt as follows −

$javac HyperlinkEX.java
$java HyperlinkEX

它将在你的当前目录中生成一个名为 hyperlink.xlsx 的 Excel 文件并在命令提示符上显示以下输出。

It will generate an Excel file named hyperlink.xlsx in your current directory and display the following output on the command prompt.

hyperlink.xlsx written successfully

hyperlink.xlsx 文件看起来如下 −

The hyperlink.xlsx file looks as follows −

hyperlink

Apache POI - Print Area

这一章解释了如何在电子表格上设置打印区域。在 Excel 电子表格中,常见的打印区域是从左上角打印到右下角。可以根据你的要求定制打印区域。这意味着你可以从整个电子表格打印特定范围的单元格,自定义纸张大小,在网格线打开的情况下打印内容,等等。

This chapter explains how to set the print area on a spreadsheet. The usual print area is from left top to right bottom on Excel spreadsheets. Print area can be customized according to your requirement. It means you can print a particular range of cells from the whole spreadsheet, customize the paper size, print the contents with the grid lines turned on, etc.

以下代码用于在电子表格上设置打印区域。

The following code is used to set up the print area on a spreadsheet.

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFPrintSetup;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class PrintArea
{
   public static void main(String[] args)throws Exception
   {
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook
      .createSheet("Print Area");
      //set print area with indexes
      workbook.setPrintArea(
         0, //sheet index
         0, //start column
         5, //end column
         0, //start row
         5 //end row
      );
      //set paper size
      spreadsheet.getPrintSetup().setPaperSize(
      XSSFPrintSetup.A4_PAPERSIZE);
      //set display grid lines or not
      spreadsheet.setDisplayGridlines(true);
      //set print grid lines or not
      spreadsheet.setPrintGridlines(true);
      FileOutputStream out = new FileOutputStream(
      new File("printarea.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("printarea.xlsx written successfully");
   }
}

让我们将以上代码保存在文件中 PrintArea.java 。从命令提示符编译并执行代码,如下所示:

Let us save the above code as PrintArea.java. Compile and execute it from the command prompt as follows −

$javac PrintArea.java
$java PrintArea

它将在你的当前目录中生成一个名为 printarea.xlsx 的文件,然后在命令提示符上显示以下输出。

It will generate a file named printarea.xlsx in your current directory and display the following output on the command prompt.

printarea.xlsx written successfully

在以上代码中,我们没有添加任何单元格值。因此 printarea.xlsx 是一个空白文件。但你可以观察到,在下图中,打印预览显示了带有网格线的打印区域。

In the above code, we have not added any cell values. Hence printarea.xlsx is a blank file. But you can observe in the following figure that the print preview shows the print area with grid lines.

printarea

Apache POI - Database

本章介绍 POI 库如何与数据库交互。借助 JDBC,您可以从数据库中检索数据并使用 POI 库将该数据插入到电子表格中。让我们考虑使用 MySQL 数据库进行 SQL 操作。

This chapter explains how the POI library interacts with a database. With the help of JDBC, you can retrieve data from a database and insert that data into a spreadsheet using the POI library. Let us consider MySQL database for SQL operations.

Write into Database

让我们假设要从 MySQL 数据库 test 中检索以下名为 emp_tbl 的员工数据表。

Let us assume the following employee data table called emp_tbl is to be retrieved from the MySQL database test.

EMP ID

EMP NAME

DEG

SALARY

DEPT

1201

Gopal

Technical Manager

45000

IT

1202

Manisha

Proof reader

45000

Testing

1203

Masthanvali

Technical Writer

45000

IT

1204

Kiran

Hr Admin

40000

HR

1205

Kranthi

Op Admin

30000

Admin

使用以下代码从数据库中检索数据并将其插入电子表格。

Use the following code to retrieve data from a database and insert the same into a spreadsheet.

import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDatabase {
   public static void main(String[] args) throws Exception {
      Class.forName("com.mysql.jdbc.Driver");
      Connection connect = DriverManager.getConnection(
         "jdbc:mysql://localhost:3306/test" ,
         "root" ,
         "root"
      );
      Statement statement = connect.createStatement();
      ResultSet resultSet = statement
      .executeQuery("select * from emp_tbl");
      XSSFWorkbook workbook = new XSSFWorkbook();
      XSSFSheet spreadsheet = workbook
      .createSheet("employe db");
      XSSFRow row=spreadsheet.createRow(1);
      XSSFCell cell;
      cell=row.createCell(1);
      cell.setCellValue("EMP ID");
      cell=row.createCell(2);
      cell.setCellValue("EMP NAME");
      cell=row.createCell(3);
      cell.setCellValue("DEG");
      cell=row.createCell(4);
      cell.setCellValue("SALARY");
      cell=row.createCell(5);
      cell.setCellValue("DEPT");
      int i=2;
      while(resultSet.next()) {
         row=spreadsheet.createRow(i);
         cell=row.createCell(1);
         cell.setCellValue(resultSet.getInt("eid"));
         cell=row.createCell(2);
         cell.setCellValue(resultSet.getString("ename"));
         cell=row.createCell(3);
         cell.setCellValue(resultSet.getString("deg"));
         cell=row.createCell(4);
         cell.setCellValue(resultSet.getString("salary"));
         cell=row.createCell(5);
         cell.setCellValue(resultSet.getString("dept"));
         i++;
      }
      FileOutputStream out = new FileOutputStream(
      new File("exceldatabase.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("exceldatabase.xlsx written successfully");
   }
}

让我们将上述代码另存为 ExcelDatabase.java 。如下所示从命令提示符对其进行编译并执行。

Let us save the above code as ExcelDatabase.java. Compile and execute it from the command prompt as follows.

$javac ExcelDatabase.java
$java ExcelDatabase

它将在您当前的目录中生成一个名为 exceldatabase.xlsx 的 Excel 文件,并在命令提示符中显示以下输出。

It will generate an Excel file named exceldatabase.xlsx in your current directory and display the following output on the command prompt.

exceldatabase.xlsx written successfully

exceldatabase.xlsx 文件如下所示:

The exceldatabase.xlsx file looks as follows −

exceldatabase