问题描述
我需要生成一个 .xls (Excel) 文件,使用 Java 库 Apache POI 用于电子表格.
I need to generate an .xls (Excel) file, using the Java library Apache POI for spreadsheets.
该文件将包含 A 列中的电话号码列表,格式为0221...."或+49221..." - 因此 Excel 默认将它们解释为数字单元格.这很糟糕,因为前导 0 或 + 将被修剪.
The file will contain a list of phone numbers in column A, formatted as "0221...." or "+49221..." - so Excel by default interprets them as numeric cells. This is bad, because the leading 0 or + will get trimmed.
为了解决这个问题,我可以使用 cell.setCellType(Cell.CELL_TYPE_STRING)
,它工作正常,但仅适用于我设置的特定单元格.
To solve the problem, I can use cell.setCellType(Cell.CELL_TYPE_STRING)
, which works fine, but only for the specific cells I set this for.
我如何为整列应用此设置(即,即使对于所有剩余的单元格,用户将在其中输入额外的电话号码)?
How can I apply this setting for the entire column (i.e. even for all the remaining cells, where the user will enter additional phone numbers)?
在 Excel 中,这是可能的:选择整列,并应用单元格类型(该设置在保存/加载文件后仍然有效.)
In Excel, this is possible: Selecting the entire column, and apply the cell type (the setting survives saving/loading the file.)
但是我找不到正确的 POI 方法.
But I can't find the correct method for POI.
- 首先我假设它应该类似于
sheet.setDefaultCellType(int colNum)
.但我找不到这样的东西(可能我只是瞎了?有很多 库中的类似方法,用于应用对齐中心"等文本样式)立> - 然后我想:也许它只能应用于 NamedRange 或类似的东西,但我还没有弄清楚这是如何工作的......
- First I assumed, it should be something like
sheet.setDefaultCellType(int colNum)
. But I can't find anything like this (probably I'm just blind? There are lots of similar methods in the library for applying text styles like "align center" etc.) - Then I thought: Maybe it can only be applied to a NamedRange or something similar, but I haven't managed to work out how this works...
推荐答案
Will 这个有帮助吗?
通过使用@ 符号创建数据格式并在 CellStyle 中使用它然后传递给 setDefaultColumnStyle() 方法的对象,它是可以将列的默认数据类型设置为文本,在本例中.我没有进一步实验,但怀疑有可能做到与其他样式对象类似的东西将默认类型设置为数字甚至自定义格式,例如货币.
这篇关于Apache POI for Excel:将单元格类型设置为“文本"对于整列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!