Busy Developers' Guide to HSSF and XSSF Features(给忙成狗的开发者的HSSF和XSSF功能指南)
Busy Developers' Guide to Features(给忙成狗的开发者的HSSF和XSSF功能指南)
Want to use HSSF and XSSF read and write spreadsheets in a hurry? This guide is for you. If you're after more in-depth coverage of the HSSF and XSSF user-APIs, please consult the HOWTO guide as it contains actual descriptions of how to use this stuff.(想要快速使用 HSSF 和 XSSF 读写电子表格?本指南适合您。如果您想要更深入地了解 HSSF 和 XSSF 用户 API,请参阅HOWTO指南,因为它包含有关如何使用这些内容的描述。)
Index of Features(特征索引)
- How to create a new workbook(如何创建新工作簿)
- How to create a sheet(如何创建工作表)
- How to create cells(如何创建单元格)
- How to create date cells(如何创建日期单元格)
- Working with different types of cells(使用不同类型的单元格)
- Iterate over rows and cells(迭代行和单元格)
- Getting the cell contents(获取单元格内容)
- Text Extraction(文本提取)
- Files vs InputStreams(文件与输入流)
- Aligning cells(对齐单元格)
- Working with borders(使用边框)
- Fills and color(填充和颜色)
- Merging cells(合并单元格)
- Working with fonts(使用字体)
- Custom colors(自定义颜色)
- Reading and writing(读和写)
- Use newlines in cells.(在单元格中使用换行符)
- Create user defined data formats(创建用户定义的数据格式)
- Fit Sheet to One Page(将工作表设置为一页(打印设置))
- Set print area for a sheet(设置工作表的打印区域)
- Set page numbers on the footer of a sheet(在工作表的页脚上设置页码)
- Shift rows(移动行)
- Set a sheet as selected(将工作表设置为选中)
- Set the zoom magnification for a sheet(设置工作表的缩放倍率)
- Create split and freeze panes(创建拆分和冻结窗格)
- Repeating rows and columns(重复行和列)
- Headers and Footers(页眉和页脚)
- XSSF enhancement for Headers and Footers(页眉和页脚的XSSF增强)
- Drawing Shapes(绘制形状)
- Styling Shapes(样式形状)
- Shapes and Graphics2d(形状和Graphics2d)
- Outlining(概述)
- Images(图片)
- Named Ranges and Named Cells(范围命名和单元格命名)
- How to set cell comments(如何设置单元格注释)
- How to adjust column width to fit the contents(如何调整列宽以适应内容)
- Hyperlinks(超链接)
- Data Validations(数据验证)
- Embedded Objects(嵌入对象)
- Autofilters(自动过滤器)
- Conditional Formatting(条件格式)
- Hiding and Un-Hiding Rows(隐藏和显示隐藏行)
- Setting Cell Properties(设置单元格属性)
- Drawing Borders(绘制边框)
- Create a Pivot Table(创建数据透视表)
- Cells with multiple styles(具有多种样式的单元格)
Features(特征)
New Workbook(新工作簿)
New Sheet(新工作表)
// 并且不得包含以下任何字符:
// 0x0000
// 0x0003
// 冒号 (:)
// 反斜杠 (\)
// 星号 (* )
// 问号 (?)
// 正斜杠 (/)
// 左方括号 ([)
// 右方括号 (])
// 为了安全地创建有效名称,此实用程序将无效字符替换为空格 (' ')
Creating Cells(创建单元格)
Creating Date Cells(创建日期单元格)
//从工作簿中创建一个新的单元格样式很重要,否则可能会修改内置样式,不仅影响此单元格,还会影响其他单元格。
Working with different types of cells(使用不同类型的单元格)
Files vs InputStreams(文件与输入流)
When opening a workbook, either a .xls HSSFWorkbook, or a .xlsx XSSFWorkbook, the Workbook can be loaded from either a File or an InputStream. Using a File object allows for lower memory consumption, while an InputStream requires more memory as it has to buffer the whole file.(打开工作簿(.xls HSSFWorkbook 或 .xlsx XSSFWorkbook)时,可以从File或InputStream加载工作簿。使用 File 对象可以降低内存消耗,而InputStream需要更多内存,因为它必须缓冲整个文件。)
If using WorkbookFactory, it's very easy to use one or the other:(如果使用 WorkbookFactory,那么使用其中一个非常容易:)
If using HSSFWorkbook or XSSFWorkbook directly, you should generally go through POIFSFileSystem or OPCPackage, to have full control of the lifecycle (including closing the file when done):(如果直接使用 HSSFWorkbook 或 XSSFWorkbook,一般应该通过 POIFSFileSystem 或 OPCPackage 来完全控制生命周期(包括完成后关闭文件):)
Demonstrates various alignment options(演示各种对齐选项)
* 创建一个单元格并以某种方式对齐它.
*
* @param wb 工作簿对象
* @param row 用于创建单元格的行
* @param column 单元格的列号
* @param halign 单元格的水平对齐方式
* @param valign 单元格的垂直对齐方式
*/
Working with borders(使用边框)
Iterate over rows and cells(迭代行和单元格)
Sometimes, you'd like to just iterate over all the sheets in a workbook, all the rows in a sheet, or all the cells in a row. This is possible with a simple for loop.(有时,您只想遍历工作簿中的所有工作表、工作表中的所有行或一行中的所有单元格。这可以通过一个简单的 for 循环来实现。)
These iterators are available by calling workbook.sheetIterator(), sheet.rowIterator(), and row.cellIterator(), or implicitly using a for-each loop. Note that a rowIterator and cellIterator iterate over rows or cells that have been created, skipping empty rows and cells.(这些迭代器可通过调用 workbook.sheetIterator()、sheet.rowIterator() 和 row.cellIterator() 或隐式使用 for-each 循环获得。请注意,rowIterator 和 cellIterator 遍历已创建的行或单元格,跳过空行和单元格。)
Iterate over cells, with control of missing / blank cells(迭代单元格,控制缺失/空白单元格)
In some cases, when iterating, you need full control over how missing or blank rows and cells are treated, and you need to ensure you visit every cell and not just those defined in the file. (The CellIterator will only return the cells defined in the file, which is largely those with values or stylings, but it depends on Excel).(在某些情况下,在迭代时,您需要完全控制丢失或空白行和单元格的处理方式,并且您需要确保访问每个单元格,而不仅仅是文件中定义的单元格。 (CellIterator 将只返回文件中定义的单元格,主要是那些具有值或样式的单元格,这取决于 Excel)。)
In cases such as these, you should fetch the first and last column information for a row, then call getCell(int, MissingCellPolicy) to fetch the cell. Use a MissingCellPolicy to control how blank or null cells are handled.(在这种情况下,您应该获取一行的第一列和最后一列信息,然后调用 getCell(int, MissingCellPolicy) 来获取单元格。使用 MissingCellPolicy控制如何处理空白或空单元格。)
// 根据需要处理
Getting the cell contents(获取单元格内容)
To get the contents of a cell, you first need to know what kind of cell it is (asking a string cell for its numeric contents will get you a NumberFormatException for example). So, you will want to switch on the cell's type, and then call the appropriate getter for that cell.(要获取单元格的内容,您首先需要知道它是什么类型的单元格(例如,向字符串单元格获取一个数字内容会得到一个 NumberFormatException)。因此,您需要获取单元格的类型,然后对该单元格调用适当的 getter方法。)
In the code below, we loop over every cell in one sheet, print out the cell's reference (eg A3), and then the cell's contents.(在下面的代码中,我们循环遍历一张表中的每个单元格,打印出单元格的引用(例如A3、Sheet1!A3),然后打印出单元格的内容。)
//DataFormatter.formatCellValue(Cell cell)无论单元格类型如何,都将单元格的格式化值作为字符串返回
Text Extraction(文本提取)
For most text extraction requirements, the standard ExcelExtractor class should provide all you need.(对于大多数文本提取要求,标准 ExcelExtractor 类应该满足您的需要。)
For very fancy text extraction, XLS to CSV etc, take a look at /src/examples/src/org/apache/poi/examples/hssf/eventusermodel/XLS2CSVmra.java(对于非常花哨的文本提取、XLS 到 CSV 等,请查看 /src/examples/src/org/apache/poi/examples/hssf/eventusermodel/XLS2CSVmra.java)
Fills and colors(填充和颜色)
Merging cells(合并单元格)
Working with fonts(使用字体)
Note, the maximum number of unique fonts in a workbook is limited to 32767. You should re-use fonts in your applications instead of creating a font for each cell. Examples:(请注意,工作簿中唯一字体的最大数量限制为 32767。您应该在应用程序中重复使用字体,而不是为每个单元格创建字体。例子:)
Wrong:(错误的:)
Correct:(正确的:)
Custom colors(自定义颜色)
HSSF:(HSSF:)
XSSF:(XSSF:)
Reading and Rewriting Workbooks(读取和重写工作簿)
Using newlines in cells(在单元格中使用换行符)
Data Formats(数据格式)
Fit Sheet to One Page(将工作表设置为一页(打印设置))
Set Print Area(设置打印区域)
Set Page Numbers on Footer(在页脚设置页码)
Using the Convenience Functions(使用便捷函式)
The convenience functions provide utility features such as setting borders around merged regions and changing style attributes without explicitly creating new styles.(便捷函式提供实用功能,例如在合并区域周围设置边框和更改样式属性而无需显式创建新样式。)
Shift rows up or down on a sheet(在工作表上向上或向下移动行)
Set a sheet as selected(将工作表设置为选中)
Set the zoom magnification(设置缩放倍率)
The zoom is expressed as a fraction. For example to express a zoom of 75% use 3 for the numerator and 4 for the denominator.(缩放以分数表示。例如,要表示 75% 的缩放,分子使用 3,分母使用 4。)
Splits and freeze panes(拆分和冻结窗格)
There are two types of panes you can create; freeze panes and split panes.(您可以创建两种类型的窗格;冻结窗格和拆分窗格。)
A freeze pane is split by columns and rows. You create a freeze pane using the following mechanism:(冻结窗格按列和行进行冻结,您可以使用以下机制创建冻结窗格:)
sheet1.createFreezePane( 3, 2, 3, 2 );(sheet1.createFreezePane(3,2,3,2);)
The first two parameters are the columns and rows you wish to split by. The second two parameters indicate the cells that are visible in the bottom right quadrant.(前两个参数是您希望冻结的列和行。后两个参数表示右下象限中可见的单元格。)
Split panes appear differently. The split area is divided into four separate work area's. The split occurs at the pixel level and the user is able to adjust the split by dragging it to a new position.(拆分窗格的显示方式不同。分割区域分为四个独立的工作区域。分割发生在像素级别,用户可以通过将分割拖动到新位置来调整。)
Split panes are created with the following call:(拆分窗格是通过以下调用创建的:)
sheet2.createSplitPane( 2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT );(sheet2.createSplitPane(2000, 2000, 0, 0, Sheet.PANE_LOWER_LEFT);)
The first parameter is the x position of the split. This is in 1/20th of a point. A point in this case seems to equate to a pixel. The second parameter is the y position of the split. Again in 1/20th of a point.(第一个参数是分割的x位置。它是一个点的 1/20。在这种情况下,一个点大概等同于一个像素。第二个参数是分割的y位置,也是一个点的1/20。)
The last parameter indicates which pane currently has the focus. This will be one of Sheet.PANE_LOWER_LEFT, PANE_LOWER_RIGHT, PANE_UPPER_RIGHT or PANE_UPPER_LEFT.(最后一个参数指示当前哪个窗格具有焦点。这将是 Sheet.PANE_LOWER_LEFT、PANE_LOWER_RIGHT、PANE_UPPER_RIGHT 或 PANE_UPPER_LEFT 之一。)
Repeating rows and columns(重复行和列)
It's possible to set up repeating rows and columns in your printouts by using the setRepeatingRows() and setRepeatingColumns() methods in the Sheet class.(可以使用 Sheet 类中的 setRepeatingRows() 和 setRepeatingColumns() 方法在打印输出中设置重复的行和列。)
These methods expect a CellRangeAddress parameter which specifies the range for the rows or columns to repeat. For setRepeatingRows(), it should specify a range of rows to repeat, with the column part spanning all columns. For setRepeatingColums(), it should specify a range of columns to repeat, with the row part spanning all rows. If the parameter is null, the repeating rows or columns will be removed.(这些方法需要一个 CellRangeAddress 参数,该参数指定要重复的行或列的范围。对于 setRepeatingRows(),它应该指定要重复的行范围,列部分跨越所有列。对于 setRepeatingColums(),它应该指定要重复的列范围,其中行部分跨越所有行。如果该参数为空,则将删除重复的行或列。)
Headers and Footers(页眉和页脚)
Example is for headers but applies directly to footers.(示例适用于页眉,也适用于页脚。)
XSSF Enhancement for Headers and Footers(页眉和页脚的 XSSF 增强)
Example is for headers but applies directly to footers. Note, the above example for basic headers and footers applies to XSSF Workbooks as well as HSSF Workbooks. The HSSFHeader stuff does not work for XSSF Workbooks.(示例适用于页眉,也适用于页脚。请注意,上述基本页眉和页脚示例适用于 XSSF 工作簿以及 HSSF 工作簿。 HSSFHeader 内容不适用于 XSSF 工作簿。)
XSSF has the ability to handle First page headers and footers, as well as Even/Odd headers and footers. All Header/Footer Property flags can be handled in XSSF as well. The odd header and footer is the default header and footer. It is displayed on all pages that do not display either a first page header or an even page header. That is, if the Even header/footer does not exist, then the odd header/footer is displayed on even pages. If the first page header/footer does not exist, then the odd header/footer is displayed on the first page. If the even/odd property is not set, that is the same as the even header/footer not existing. If the first page property does not exist, that is the same as the first page header/footer not existing.(XSSF 能够处理首页页眉和页脚,以及偶数/奇数页眉和页脚。所有页眉/页脚属性标志也可以在 XSSF 中处理。奇数页眉和页脚是默认页眉和页脚。它显示在除了首页标题或偶数页标题的所有页面上。也就是说,如果偶数页眉/页脚不存在,则奇数页眉/页脚将显示在偶数页上。如果第一页页眉/页脚不存在,则奇数页眉/页脚显示在第一页上。如果未设置偶数/奇数属性,则与相当于不存在偶数页眉/页脚。如果首页页属性不存在,则相当于首页页眉/页脚不存在。)
Drawing Shapes(绘制形状)
POI supports drawing shapes using the Microsoft Office drawing tools. Shapes on a sheet are organized in a hierarchy of groups and and shapes. The top-most shape is the patriarch. This is not visible on the sheet at all. To start drawing you need to call createPatriarch on the HSSFSheet class. This has the effect erasing any other shape information stored in that sheet. By default POI will leave shape records alone in the sheet unless you make a call to this method.(POI 支持使用 Microsoft Office 绘图工具绘制图形。工作表上的图形根据组和图形的层次结构进行组织,顶层图形叫做“族长”,它们在工作表上并不可见。要开始绘图,您需要在 HSSFSheet 类上调用 createPatriarch。这会删除该工作表中存储的任何其他图形信息。默认情况下,除非您调用此方法,否则 POI 将在工作表中保留图形记录。)
To create a shape you have to go through the following steps:(要创建图形,您必须执行以下步骤:)
- Create the patriarch.(创建“族长”。)
- Create an anchor to position the shape on the sheet.(创建一个锚点以将形状定位在图纸上。)
- Ask the patriarch to create the shape.(使用“族长”创建图形。)
- Set the shape type (line, oval, rectangle etc...)(设置图形类型(线、椭圆、矩形等...))
- Set any other style details concerning the shape. (eg: line thickness, etc...)(设置图形的其他样式细节。 (例如:线条粗细等...))
Text boxes are created using a different call:(文本框是调用另一个方法创建的:)
It's possible to use different fonts to style parts of the text in the textbox. Here's how:(可以使用不同的字体来设置文本框中部分文本的样式。比如这样:)
Just as can be done manually using Excel, it is possible to group shapes together. This is done by calling createGroup() and then creating the shapes using those groups.(图形可以进行分组,就像使用Excel手动操作一样。可以通过调用 createGroup() 然后使用这些组创建图形。)
It's also possible to create groups within groups.(也可以在组内创建组。)
Here's how to create a shape group:(以下是创建图形组的方法:)
If you're being observant you'll noticed that the shapes that are added to the group use a new type of anchor: the HSSFChildAnchor. What happens is that the created group has it's own coordinate space for shapes that are placed into it. POI defaults this to (0,0,1023,255) but you are able to change it as desired. Here's how:(如果您仔细观察,您会注意到添加到组中的形状使用了一种新类型的锚:HSSFChildAnchor。因为放置在组中的图形拥有相对于组的坐标空间。POI 默认为 (0,0,1023,255),但您可以根据需要更改它。比如这样:)
If you create a group within a group it's also going to have it's own coordinate space.(如果您在组内创建一个组,它也将拥有自己的坐标空间。)
Styling Shapes(图形样式)
By default shapes can look a little plain. It's possible to apply different styles to the shapes however. The sorts of things that can currently be done are:(默认情况下,图形看上去很简单。但是,可以对图形应用不同的样式来让它变得花哨。目前可以这样做:)
- Change the fill color.(更改填充颜色。)
- Make a shape with no fill color.(创建一个没有填充颜色的图形。)
- Change the thickness of the lines.(更改线条的粗细。)
- Change the style of the lines. Eg: dashed, dotted.(更改线条的样式。如:虚线、点线。)
- Change the line color.(更改线条颜色。)
Here's an examples of how this is done:(下述代码演示如何完成:)
Shapes and Graphics2d(图形和Graphics2d)
While the native POI shape drawing commands are the recommended way to draw shapes in a shape it's sometimes desirable to use a standard API for compatibility with external libraries. With this in mind we created some wrappers for Graphics and Graphics2d.(虽然本机POI图形绘制命令是在图形中绘制图形的推荐方法,但有时需要使用标准 API 以与外部库兼容。考虑到这一点,我们为 Graphics 和 Graphics2d 创建了一些包装器。)
All Graphics commands are issued into an HSSFShapeGroup. Here's how it's done:(所有图形命令都会发送到一个 HSSFShapeGroup。下述代码演示如何完成:)
The first thing we do is create the group and set it's coordinates to match what we plan to draw. Next we calculate a reasonable fontSizeMultiplier then create the EscherGraphics object. Since what we really want is a Graphics2d object we create an EscherGraphics2d object and pass in the graphics object we created. Finally we call a routine that draws into the EscherGraphics2d object.(我们要做的第一件事是创建组并设置它的坐标以匹配我们计划绘制的内容。接下来我们计算一个合理的 fontSizeMultiplier 然后创建 EscherGraphics 对象。因为我们真正想要的是一个 Graphics2d 对象,所以我们创建一个 EscherGraphics2d 对象并传入我们创建的图形对象。最后,我们调用一个绘制到 EscherGraphics2d 对象中的例程。)
The vertical points per pixel deserves some more explanation. One of the difficulties in converting Graphics calls into escher drawing calls is that Excel does not have the concept of absolute pixel positions. It measures it's cell widths in 'characters' and the cell heights in points. Unfortunately it's not defined exactly what type of character it's measuring. Presumably this is due to the fact that the Excel will be using different fonts on different platforms or even within the same platform.(每个像素的垂直点需要更多解释。将 Graphics转换为Escher绘图的困难之一是 Excel 没有绝对像素位置的概念。它以“字符”为单位测量其单元格宽度和以点为单位的单元格高度。不幸的是,它没有准确定义它正在测量的字符类型。这大概是由于Excel在不同平台上甚至在同一平台内使用不同的字体。)
Because of this constraint we've had to implement the concept of a verticalPointsPerPixel. This the amount the font should be scaled by when you issue commands such as drawString(). To calculate this value use the follow formula:(由于这个限制,我们不得不实现verticalPointsPerPixel 的概念,它是当您发出诸如 drawString() 之类的命令时字体应该被缩放的值。要计算此值,请使用以下公式:)
The height of the group is calculated fairly simply by calculating the difference between the y coordinates of the bounding box of the shape. The height of the group can be calculated by using a convenience called HSSFClientAnchor.getAnchorHeightInPoints().(通过计算图形边界框的y坐标之间的距离,可以相当简单地计算组的高度。组的高度可以通过使用HSSFClientAnchor.getAnchorHeightInPoints() 来便捷计算。)
Many of the functions supported by the graphics classes are not complete. Here's some of the functions that are known to work.(图形类支持的很多功能并不完整。以下是一些已知的有用的功能。)
- fillRect()(fillRect() 填充矩形)
- fillOval()(fillOval() 填充椭圆)
- drawString()(drawString() 绘制字符串)
- drawOval()(drawOval() 绘制椭圆)
- drawLine()(drawLine() 画线)
- clearRect()(clearRect() 清除矩形)
Functions that are not supported will return and log a message using the POI logging infrastructure (disabled by default).(不受支持的函数将使用POI日志基础结构返回并记录消息(默认情况下禁用)。)
Outlining(概述)
Outlines are great for grouping sections of information together and can be added easily to columns and rows using the POI API. Here's how:(大纲非常适合将信息部分组合在一起,并且可以使用 POI API 轻松添加到列和行中。如下所示:)
To collapse (or expand) an outline use the following calls:(要折叠(或展开)大纲,请使用以下调用:)
The row/column you choose should contain an already created group. It can be anywhere within the group.(您选择的行/列应包含已创建的组。它可以是组内的任何位置。)
Images(图片)
Images are part of the drawing support. To add an image just call createPicture() on the drawing patriarch. At the time of writing the following types are supported:(图像是绘图支持的一部分。要添加图像,只需在绘图族长上调用 createPicture()。在撰写本文时,它支持以下图片类型:)
- PNG(PNG)
- JPG(JPG)
- DIB(DIB)
It should be noted that any existing drawings may be erased once you add a image to a sheet.(应该注意的是,一旦您将图像添加到工作表,任何现有的图纸都可能会被删除。)
Reading images from a workbook:(从工作簿中读取图像:)
Named Ranges and Named Cells(命名范围和命名单元格)
Named Range is a way to refer to a group of cells by a name. Named Cell is a degenerate case of Named Range in that the 'group of cells' contains exactly one cell. You can create as well as refer to cells in a workbook by their named range. When working with Named Ranges, the classes org.apache.poi.ss.util.CellReference and org.apache.poi.ss.util.AreaReference are used.(命名范围是一种通过名称引用一组单元格的方法。命名单元格是命名范围的退化情况,因为“单元格组”仅包含一个单元格。您可以通过命名范围创建和引用工作簿中的单元格。使用命名范围时,使用类 org.apache.poi.ss.util.CellReference 和 org.apache.poi.ss.util.AreaReference。)
Note: Using relative values like 'A1:B1' can lead to unexpected moving of the cell that the name points to when working with the workbook in Microsoft Excel, usually using absolute references like '$A$1:$B$1' avoids this, see also this discussion.(注意:在 Microsoft Excel 中使用工作簿时,使用像“A1:B1”这样的相对值可能会导致名称指向的单元格发生意外移动,通常使用像“$A$1:$B$1”这样的绝对引用可以避免这种情况,另见此讨论。)
Creating Named Range / Named Cell(创建命名范围/命名单元格)
Reading from Named Range / Named Cell(从命名范围/命名单元格中读取)
Reading from non-contiguous Named Ranges(从不连续的命名范围中读取)
// 类似于 "$C$10,$D$12:$D$14";
// 将返回C10的一个区域引用,以及D12到D14的另一个区域引用
Note, when a cell is deleted, Excel does not delete the attached named range. As result, workbook can contain named ranges that point to cells that no longer exist. You should check the validity of a reference before constructing AreaReference(请注意,删除单元格时,Excel 不会删除附加的命名范围。因此,工作簿可以包含指向不再存在的单元格的命名范围。您应该在构建 AreaReference 之前检查引用的有效性)
Cell Comments - HSSF and XSSF(单元格注释 - HSSF 和 XSSF)
A comment is a rich text note that is attached to & associated with a cell, separate from other cell content. Comment content is stored separate from the cell, and is displayed in a drawing object (like a text box) that is separate from, but associated with, a cell(注释是附加到单元格并与单元格相关联的富文本注释,与其他单元格内容不相干。注释内容与单元格分开存储,并显示在与单元格分开但与单元格相关联的绘图对象(如文本框)中)
Reading cell comments(读取单元格注释)
To get all the comments on a sheet:(获取工作表上的所有注释:)
Adjust column width to fit the contents(调整列宽以适应内容)
For SXSSFWorkbooks only, because the random access window is likely to exclude most of the rows in the worksheet, which are needed for computing the best-fit width of a column, the columns must be tracked for auto-sizing prior to flushing any rows.(仅对于 SXSSFWorkbooks,由于随机访问窗口可能会排除工作表中的大多数行,而这些行是计算列的最佳适应宽度所需的,因此必须在刷新任何行之前跟踪列以自动调整大小。)
// 或者,如果事先不知道将自动调整大小的列,或者您正在升级现有代码并试图最小化更改,则使用 SXSSFSheet#trackAllColumnsForAutoSizing()。请记住,跟踪所有列将需要更多的内存和CPU周期,因为在刷新的每一行的所有跟踪列上都会计算最佳拟合宽度。
Note, that Sheet#autoSizeColumn() does not evaluate formula cells, the width of formula cells is calculated based on the cached formula result. If your workbook has many formulas then it is a good idea to evaluate them before auto-sizing.(请注意,Sheet#autoSizeColumn() 不会计算公式单元格,公式单元格的宽度是根据缓存的公式结果计算的。如果您的工作簿有许多公式,那么在自动调整大小之前评估它们是个好主意。)
How to read hyperlinks(如何读取超链接)
How to create hyperlinks(如何创建超链接)
//默认情况下超链接是蓝色的并带有下划线
Data Validations(数据验证)
As of version 3.8, POI has slightly different syntax to work with data validations with .xls and .xlsx formats.(从 3.8 版开始,POI 使用 .xls 和 .xlsx 格式的数据验证的语法略有不同。)
hssf.usermodel (binary .xls format)(hssf.usermodel (binary .xls format))
Check the value a user enters into a cell against one or more predefined value(s).(对照一个或多个预定义值检查用户在单元格中输入的值。)
The following code will limit the value the user can enter into cell A1 to one of three integer values, 10, 20 or 30.(以下代码将用户可以在单元格 A1 中输入的值限制为三个整数值之一,即 10、20 或 30。)
Drop Down Lists:(下拉列表:)
This code will do the same but offer the user a drop down list to select a value from.(此代码将执行相同的操作,但会为用户提供一个下拉列表以从中选择一个值。)
Messages On Error:(错误消息:)
To create a message box that will be shown to the user if the value they enter is invalid.(创建一个消息框,如果用户输入的值无效,该消息框将显示。)
Replace 'Box Title' with the text you wish to display in the message box's title bar and 'Message Text' with the text of your error message.(将“框标题”替换为您希望在消息框标题栏中显示的文本,将“消息文本”替换为错误消息的文本。)
Prompts:(提示:)
To create a prompt that the user will see when the cell containing the data validation receives focus(创建一个提示,当包含数据验证的单元格获得焦点时,用户将看到该提示)
The text encapsulated in the first parameter passed to the createPromptBox() method will appear emboldened and as a title to the prompt whilst the second will be displayed as the text of the message. The createExplicitListConstraint() method can be passed and array of String(s) containing interger, floating point, dates or text values.(传递给 createPromptBox() 方法的第一个参数中封装的文本将显示为粗体并作为提示的标题,而第二个参数将显示为消息的文本。createExplicitListConstraint()方法可以使用包含整数、浮点、日期或文本值的字符串数组。)
Further Data Validations:(进一步的数据验证:)
To obtain a validation that would check the value entered was, for example, an integer between 10 and 100, use the DVConstraint.createNumericConstraint(int, int, String, String) factory method.(要获得并检查输入的值是否为 10 到 100 之间的整数,请使用 DVConstraint.createNumericConstraint(int, int, String, String) 工厂方法。)
Look at the javadoc for the other validation and operator types; also note that not all validation types are supported for this method. The values passed to the two String parameters can be formulas; the '=' symbol is used to denote a formula(查看 javadoc 以了解其他验证和运算符类型;另请注意,此方法并非支持所有验证类型。传递给两个 String 参数的值可以是公式; '=' 符号用于表示公式)
It is not possible to create a drop down list if the createNumericConstraint() method is called, the setSuppressDropDownArrow(false) method call will simply be ignored.(如果调用 createNumericConstraint() 方法,则无法创建下拉列表,setSuppressDropDownArrow(false) 方法调用将被忽略。)
Date and time constraints can be created by calling the createDateConstraint(int, String, String, String) or the createTimeConstraint(int, String, String). Both are very similar to the above and are explained in the javadoc.(可以通过调用 createDateConstraint(int, String, String, String) 或 createTimeConstraint(int, String, String) 来创建日期和时间约束。两者与上述所说非常相似,并在 javadoc 中有说明。)
Creating Data Validations From Spreadsheet Cells.(从电子表格单元格创建数据验证。)
The contents of specific cells can be used to provide the values for the data validation and the DVConstraint.createFormulaListConstraint(String) method supports this. To specify that the values come from a contiguous range of cells do either of the following:(特定单元格的内容可用于为数据验证提供值,DVConstraint.createFormulaListConstraint(String) 方法支持这一点。要指定验证的值来自连续的单元格范围,请执行以下任一操作:)
or(或者)
and in both cases the user will be able to select from a drop down list containing the values from cells A1, A2 and A3.(在这两种情况下,用户都可以从包含单元格 A1、A2 和 A3 的值的下拉列表中进行选择。)
The data does not have to be as the data validation. To select the data from a different sheet however, the sheet must be given a name when created and that name should be used in the formula. So assuming the existence of a sheet named 'Data Sheet' this will work:(数据不一定要做数据验证。但是,要从不同的工作表中选择数据,必须在创建工作表时为工作表指定名称,并且要在公式中使用该名称。因此,假设存在名为“Data Sheet”的工作表,应该这样写:)
as will this:(就像这样:)
whilst this will not:(显然这不会起作用:)
and nor will this:(这也不会:)
xssf.usermodel (.xlsx format)(xssf.usermodel (.xlsx format))
Data validations work similarly when you are creating an xml based, SpreadsheetML, workbook file; but there are differences. Explicit casts are required, for example, in a few places as much of the support for data validations in the xssf stream was built into the unifying ss stream, of which more later. Other differences are noted with comments in the code.(当您创建基于 xml 的 SpreadsheetML 工作簿文件时,数据验证的工作方式类似;但也有区别。例如,在一些地方需要显式强制转换,因为xssf流中对数据验证的大部分支持都内置在统一的ss流中,后续会有更多支持。代码中的注释说明了其他差异)
Check the value the user enters into a cell against one or more predefined value(s).(对照一个或多个预定义值检查用户在单元格中输入的值。)
Drop Down Lists:(下拉列表:)
This code will do the same but offer the user a drop down list to select a value from.(此代码将执行相同的操作,但会为用户提供一个下拉列表以从中选择一个值。)
Note that the call to the setSuppressDropDowmArrow() method can either be simply excluded or replaced with:(请注意,对 setSuppressDropDowmArrow() 方法的调用可以不写或写成如下形式:)
Prompts and Error Messages:(提示和错误信息:)
These both exactly mirror the hssf.usermodel so please refer to the 'Messages On Error:' and 'Prompts:' sections above.(这些和hssf.usermodel中的相同,因此请参阅上面的“Messages On Error:”和“Prompts:”部分。)
Further Data Validations:(进一步的数据验证:)
To obtain a validation that would check the value entered was, for example, an integer between 10 and 100, use the XSSFDataValidationHelper(s) createNumericConstraint(int, int, String, String) factory method.(例如,要获得并检查输入值是否为 10 到 100 之间的整数,请使用 XSSFDataValidationHelper(s) createNumericConstraint(int, int, String, String) 工厂方法。)
The values passed to the final two String parameters can be formulas; the '=' symbol is used to denote a formula. Thus, the following would create a validation the allows values only if they fall between the results of summing two cell ranges(传递给最后两个 String 参数的值可以是公式; '=' 符号用于表示公式。因此,以下内容将创建一个验证,仅当值介于两个单元格范围求和的结果之间时,才允许进行验证)
It is not possible to create a drop down list if the createNumericConstraint() method is called, the setSuppressDropDownArrow(true) method call will simply be ignored.(如果调用 createNumericConstraint() 方法,则无法创建下拉列表,setSuppressDropDownArrow(true) 方法调用将被忽略。)
Please check the javadoc for other constraint types as examples for those will not be included here. There are, for example, methods defined on the XSSFDataValidationHelper class allowing you to create the following types of constraint; date, time, decimal, integer, numeric, formula, text length and custom constraints.(请检查 javadoc 以了解其他约束类型,因为这里没有这些约束类型的示例。例如,在 XSSFDataValidationHelper 类中定义的方法允许您创建以下类型的约束;日期、时间、小数、整数、数字、公式、文本长度和自定义约束。)
Creating Data Validations From Spread Sheet Cells:(从电子表格单元格创建数据验证:)
One other type of constraint not mentioned above is the formula list constraint. It allows you to create a validation that takes it value(s) from a range of cells. This code(上面未提及的另一种类型的约束是公式列表约束。它允许您创建一个从一系列单元格中获取值的验证。如下代码)
would create a validation that took it's values from cells in the range A1 to F1.(将创建一个从 A1 到 F1 范围内的单元格值的验证。)
The usefulness of this technique can be extended if you use named ranges like this;(如果您使用这样的命名范围,则可以扩展此技术的实用性;)
OpenOffice Calc has slightly different rules with regard to the scope of names. Excel supports both Workbook and Sheet scope for a name but Calc does not, it seems only to support Sheet scope for a name. Thus it is often best to fully qualify the name for the region or area something like this;(OpenOffice Calc 在名称范围方面的规则略有不同。Excel支持工作簿和工作表范围的名称,但Calc不支持,它似乎只支持工作表范围的名称。因此,通常最好完全限定该地区或区域的名称,例如:)
This does open a further, interesting opportunity however and that is to place all of the data for the validation(s) into named ranges of cells on a hidden sheet within the workbook. These ranges can then be explicitly identified in the setRefersToFormula() method argument.(然而,这带来了另一个有趣的机会,那就是将所有用于验证的数据放入工作簿中一个隐藏工作表上的命名单元格区域。然后可以在setRefersToFormula()方法参数中显式标识这些范围)
ss.usermodel(ss.usermodel)
The classes within the ss.usermodel package allow developers to create code that can be used to generate both binary (.xls) and SpreadsheetML (.xlsx) workbooks.(ss.usermodel 包中的类允许开发人员创建可用于生成二进制 (.xls) 和 SpreadsheetML (.xlsx) 工作簿的代码。)
The techniques used to create data validations share much in common with the xssf.usermodel examples above. As a result just one or two examples will be presented here.(用于创建数据验证的技术与上面的 xssf.usermodel 示例有很多共同之处。因此,这里只介绍一两个示例。)
Check the value the user enters into a cell against one or more predefined value(s).(对照一个或多个预定义值检查用户在单元格中输入的值。)
// 如果它是XSSFDataValidation类的实例,则必须将布尔值“false”传递给setSuppressDropDownArrow()方法,并显式调用setShowErrorBox()方法。
Drop Down Lists:(下拉列表:)
This code will do the same but offer the user a drop down list to select a value from.(此代码将执行相同的操作,但会为用户提供一个下拉列表以从中选择一个值。)
// 如果它是XSSFDataValidation类的实例,则必须将布尔值“false”传递给setSuppressDropDownArrow()方法,并显式调用setShowErrorBox()方法。
Prompts and Error Messages:(提示和错误信息:)
These both exactly mirror the hssf.usermodel so please refer to the 'Messages On Error:' and 'Prompts:' sections above.(这些都和 hssf.usermodel一样,因此请参阅上面的'Messages On Error:'和'Prompts:'部分。)
As the differences between the ss.usermodel and xssf.usermodel examples are small - restricted largely to the way the DataValidationHelper is obtained, the lack of any need to explicitly cast data types and the small difference in behaviour between the hssf and xssf interpretation of the setSuppressDropDowmArrow() method, no further examples will be included in this section.(由于 ss.usermodel 和 xssf.usermodel 示例之间的差异很小 - 主要限于获取 DataValidationHelper 的方式,不需要显式转换数据类型,以及SetSuppressDropDowmorrow()方法的hssf和xssf解释之间的行为差异很小,本节不再举例。)
Advanced Data Validations.(高级数据验证。)
Dependent Drop Down Lists.(从属下拉列表。)
In some cases, it may be necessary to present to the user a sheet which contains more than one drop down list. Further, the choice the user makes in one drop down list may affect the options that are presented to them in the second or subsequent drop down lists. One technique that may be used to implement this behaviour will now be explained.(在某些情况下,可能需要向用户呈现包含多个下拉列表的工作表。此外,用户在一个下拉列表中所做的选择可能会影响在第二个或后续下拉列表中呈现给他们的选项。现在将讲述可用于实现该行为的一种技术。)
There are two keys to the technique; one is to use named areas or regions of cells to hold the data for the drop down lists, the second is to use the INDIRECT() function to convert between the name and the actual addresses of the cells. In the example section there is a complete working example- called LinkedDropDownLists.java - that demonstrates how to create linked or dependent drop down lists. Only the more relevant points are explained here.(该技术有两个关键;一种是使用命名区域或单元格区域来保存下拉列表的数据,第二种是使用 INDIRECT() 函数在单元格的名称和实际地址之间进行转换。在示例部分有一个完整的工作示例——名为 LinkedDropDownLists.java——它演示了如何创建链接或依赖下拉列表。这里只解释更相关的点。)
To create two drop down lists where the options shown in the second depend upon the selection made in the first, begin by creating a named region of cells to hold all of the data for populating the first drop down list. Next, create a data validation that will look to this named area for its data, something like this;(要创建两个下拉列表,其中第二个中显示的选项取决于第一个中所做的选择,首先创建一个命名的单元格区域来保存用于填充第一个下拉列表的所有数据。接下来,创建一个数据验证,它将在这个命名区域中查找其数据,如下所示;)
Note that the name of the area - in the example above it is 'CHOICES' - is simply passed to the createFormulaListConstraint() method. This is sufficient to cause Excel to populate the drop down list with data from that named region.(请注意,区域的名称(在上面的示例中为“CHOICES”)只是传递给 createFormulaListConstraint() 方法。这足以使 Excel 使用来自该命名区域的数据填充下拉列表。)
Next, for each of the options the user could select in the first drop down list, create a matching named region of cells. The name of that region should match the text the user could select in the first drop down list. Note, in the example, all upper case letters are used in the names of the regions of cells.(接下来,对于用户可以在第一个下拉列表中选择的每个选项,创建一个匹配的命名单元格区域。该区域的名称应与用户可以在第一个下拉列表中选择的文本相匹配。请注意,在示例中,所有大写字母都用于单元格区域的名称中。)
Now, very similar code can be used to create a second, linked, drop down list;(现在,可以使用非常相似的代码来创建第二个链接的下拉列表;)
The key here is in the following Excel function - INDIRECT(UPPER($A$1)) - which is used to populate the second, linked, drop down list. Working from the inner-most pair of brackets, it instructs Excel to look at the contents of cell A1, to convert what it reads there into upper case – as upper case letters are used in the names of each region - and then convert this name into the addresses of those cells that contain the data to populate another drop down list.(这里的关键在于以下 Excel 函数 - INDIRECT(UPPER($A$1)) - 用于填充第二个链接的下拉列表。从最里面的一对括号开始,它指示 Excel 查看单元格 A1 的内容,将其中读取的内容转换为大写字母 - 因为每个区域的名称中使用大写字母 - 然后转换此名称到包含数据的单元格的地址以填充另一个下拉列表。)
Embedded Objects(嵌入对象)
It is possible to perform more detailed processing of an embedded Excel, Word or PowerPoint document, or to work with any other type of embedded object.(可以对嵌入的 Excel、Word 或 PowerPoint 文档执行更详细的处理,或者使用任何其他类型的嵌入对象。)
HSSF:(HSSF:)
// 从 HSSFObjectData 实例中恢复对象的数据。
XSSF:(XSSF:)
(Since POI-3.7)((自 POI-3.7 起))
Autofilters(自动过滤器)
Conditional Formatting(条件格式)
See more examples on Excel conditional formatting in ConditionalFormats.java(在 ConditionalFormats.java中查看有关 Excel 条件格式的更多示例)
Hiding and Un-Hiding Rows(隐藏和显示行)
Using Excel, it is possible to hide a row on a worksheet by selecting that row (or rows), right clicking once on the right hand mouse button and selecting 'Hide' from the pop-up menu that appears.(使用 Excel,可以通过选择该行(或多行)、单击鼠标右键并从出现的弹出菜单中选择“隐藏”来隐藏工作表上的一行。)
To emulate this using POI, simply call the setZeroHeight() method on an instance of either XSSFRow or HSSFRow (the method is defined on the ss.usermodel.Row interface that both classes implement), like this:(要使用 POI 进行模拟,只需在 XSSFRow 或 HSSFRow 的实例上调用 setZeroHeight() 方法(该方法在两个类都实现的 ss.usermodel.Row 接口上定义),如下所示:)
If the file were saved away to disc now, then the first row on the first sheet would not be visible.(如果现在将文件保存到光盘,则第一个工作表上的第一行将不可见。)
Using Excel, it is possible to unhide previously hidden rows by selecting the row above and the row below the one that is hidden and then pressing and holding down the Ctrl key, the Shift and the pressing the number 9 before releasing them all.(使用 Excel,可以显示隐藏的行,方法是选择隐藏行的上方和下方的行,然后按住 Ctrl 键、Shift 和按数字 9,然后再释放它们。)
To emulate this behaviour using POI do something like this:(要使用 POI 模拟此行为,请执行以下操作:)
If the file were saved away to disc now, any previously hidden rows on the first sheet of the workbook would now be visible.(如果现在将文件保存到光盘上,那么现在可以看到工作簿第一张表上以前隐藏的行。)
The example illustrates two features. Firstly, that it is possible to unhide a row simply by calling the setZeroHeight() method and passing the boolean value 'false'. Secondly, it illustrates how to test whether a row is hidden or not. Simply call the getZeroHeight() method and it will return 'true' if the row is hidden, 'false' otherwise.(该示例说明了两个功能。首先,可以简单地通过调用 setZeroHeight() 方法并传递布尔值“false”来取消隐藏一行。其次,它说明了如何测试一行是否隐藏。只需调用 getZeroHeight() 方法,如果该行被隐藏,它将返回“true”,否则返回“false”。)
Setting Cell Properties(设置单元格属性)
Sometimes it is easier or more efficient to create a spreadsheet with basic styles and then apply special styles to certain cells such as drawing borders around a range of cells or setting fills for a region. CellUtil.setCellProperties lets you do that without creating a bunch of unnecessary intermediate styles in your spreadsheet.(有时,创建具有基本样式的电子表格,然后将特殊样式应用于某些单元格,例如在一系列单元格周围绘制边框或为某个区域设置填充,会更容易或更有效。 CellUtil.setCellProperties 让您可以做到这一点,而无需在电子表格中创建一堆不必要的中间样式。)
Properties are created as a Map and applied to a cell in the following manner.(属性被创建为 Map 并以下列方式应用于单元格。)
NOTE: This does not replace the properties of the cell, it merges the properties you have put into the Map with the cell's existing style properties. If a property already exists, it is replaced with the new property. If a property does not exist, it is added. This method will not remove CellStyle properties.(注意:这不会替换单元格的属性,它会将您放入地图的属性与单元格的现有样式属性合并。如果属性已存在,则将其替换为新属性。如果属性不存在,则添加它。此方法不会删除 CellStyle 属性。)
Drawing Borders(绘制边框)
In Excel, you can apply a set of borders on an entire workbook region at the press of a button. The PropertyTemplate object simulates this with methods and constants defined to allow drawing top, bottom, left, right, horizontal, vertical, inside, outside, or all borders around a range of cells. Additional methods allow for applying colors to the borders.(在 Excel 中,您可以通过按下按钮在整个工作簿区域上应用一组边框。 PropertyTemplate 对象使用定义的方法和常量来模拟这一点,以允许在一系列单元格周围绘制顶部、底部、左侧、右侧、水平、垂直、内部、外部或所有边框。其他方法允许将颜色应用于边框。)
It works like this: you create a PropertyTemplate object which is a container for the borders you wish to apply to a sheet. Then you add borders and colors to the PropertyTemplate, and finally apply it to whichever sheets you need that set of borders on. You can create multiple PropertyTemplate objects and apply them to a single sheet, or you can apply the same PropertyTemplate object to multiple sheets. It is just like a preprinted form.(它的工作原理如下:您创建一个 PropertyTemplate 对象,该对象是您希望应用于工作表的边框的容器。然后为 PropertyTemplate 添加边框和颜色,最后将其应用到您需要该组边框的任何工作表上。您可以创建多个 PropertyTemplate 对象并将它们应用到单个工作表,也可以将相同的 PropertyTemplate 对象应用到多个工作表。它就像一个预印的表格。)
Enums:(枚举:)
- BorderStyle (边框样式)
- Defines the look of the border, is it thick or thin, solid or dashed, single or double. This enum replaces the CellStyle.BORDER_XXXXX constants which have been deprecated. The PropertyTemplate will not support the older style BORDER_XXXXX constants. A special value of BorderStyle.NONE will remove the border from a Cell once it is applied. (定义边框的外观,是粗还是细,实线还是虚线,单还是双。 此枚举替换了已弃用的 CellStyle.BORDER_XXXXX 常量。 PropertyTemplate 将不支持旧样式 BORDER_XXXXX 常量。 BorderStyle.NONE这个特殊值将在应用后从单元格中删除边框)
- BorderExtent (边框范围)
- Describes the portion of the region that the BorderStyle will apply to. For example, TOP, BOTTOM, INSIDE, or OUTSIDE. A special value of BorderExtent.NONE will remove the border from the PropertyTemplate. When the template is applied, no change will be made to a cell border where no border properties exist in the PropertyTemplate. (描述 BorderStyle 将应用于的区域部分。 例如,顶部、底部、内部或外部。 BorderExtent.NONE这个特殊值将从 PropertyTemplate 中删除边框。 应用模板时,不会对 PropertyTemplate 中不存在边框属性的单元格边框进行任何更改。)
NOTE: The last pt.drawBorders() call removes the borders from the range by using BorderStyle.NONE. Like setCellStyleProperties, the applyBorders method merges the properties of a cell style, so existing borders are changed only if they are replaced by something else, or removed only if they are replaced by BorderStyle.NONE. To remove a color from a border, use IndexedColor.AUTOMATIC.getIndex().(注意:最后一个 pt.drawBorders() 调用时使用 BorderStyle.NONE 从范围中删除边框。与 setCellStyleProperties 一样,applyBorders 方法合并单元格样式的属性,因此现有边框只有在被其他东西替换时才会更改,或者只有在被 BorderStyle.NONE 替换时才会删除。要从边框中删除颜色,请使用 IndexedColor.AUTOMATIC.getIndex()。)
Additionally, to remove a border or color from the PropertyTemplate object, use BorderExtent.NONE.(此外,要从 PropertyTemplate 对象中删除边框或颜色,请使用 BorderExtent.NONE。)
This does not work with diagonal borders yet.(这不适用于对角线边框。)
Creating a Pivot Table(创建数据透视表)
Pivot Tables are a powerful feature of spreadsheet files. You can create a pivot table with the following piece of code.(数据透视表是电子表格文件的一项强大功能。您可以使用以下代码创建数据透视表。)
//使用第一列作为行标签
Cells with multiple styles (Rich Text Strings)(具有多种样式的单元格(富文本字符串))
To apply a single set of text formatting (colour, style, font etc) to a cell, you should create a CellStyle for the workbook, then apply to the cells.(要将一组文本格式(颜色、样式、字体等)应用于单元格,您应该为工作簿创建一个 CellStyle,然后应用于单元格。)
To apply different formatting to different parts of a cell, you need to use RichTextString, which permits styling of parts of the text within the cell.(要将不同的格式应用于单元格的不同部分,您需要使用 RichTextString,它允许对单元格内的部分文本进行样式设置。)
There are some slight differences between HSSF and XSSF, especially around font colours (the two formats store colours quite differently internally), refer to the HSSF Rich Text String and XSSF Rich Text String javadocs for more details.(HSSF 和 XSSF 之间存在一些细微差别,尤其是在字体颜色方面(这两种格式在内部存储颜色完全不同),有关详细信息,请参阅 HSSF 富文本字符串和 XSSF 富文本字符串 的javadocs。)