I am using Apache POI to write data to an Excel template. The template only contains headers on the first row, but I also applied specific styles to the entire column (e.g. Accounting and Percentage).
我正在使用Apache POI将数据写入Excel模板。模板只包含第一行的标题,但我也对整个列应用了特定的样式(例如记帐和百分比)。
It would be nice to use these formats when I write data to the new cells. But if I use the createRow
and createCell
methods, the cell format is overwritten and I get General for all the cells. If I try to use getRow
and getCell
instead, I run into NullPointerExceptions retrieving the blank cell.
当我向新的单元格写入数据时,最好使用这些格式。但是如果我使用createRow和createCell方法,单元格格式就会被覆盖,我就可以对所有单元格进行通用。如果我尝试使用getRow和getCell,我将运行到nullpointerexception来检索空单元格。
Is there a way to use the pre-existing cell formatting saved in the template? Or am I stuck setting the data format myself through the API?
是否有办法使用保存在模板中的预先存在的单元格格式?还是我自己通过API设置数据格式?
Thanks for your help.
谢谢你的帮助。
2 个解决方案
#1
6
If you have applied specific styles to an entire column, then you can retrieve that CellStyle
with Sheet
's getColumnStyle
method, passing it the 0-based column index. It retrieves a normal CellStyle
object that can be used anywhere else CellStyle
s are accepted, such as in Cell
's setCellStyle
method.
如果您对整个列应用了特定的样式,那么您可以使用Sheet的getColumnStyle方法检索该CellStyle,并将基于0的列索引传递给它。它检索一个普通的CellStyle对象,该对象可以在接受CellStyle的任何地方使用,比如在Cell的setCellStyle方法中。
For avoiding the NullPointerException
, both getRow
and getCell
may return null
if the row or cell doesn't exist, respectively. You will need to call createRow
and/or createCell
to create the Cell
, on which you can always call setCellStyle
.
为了避免NullPointerException,如果行或单元格不存在,getRow和getCell都可能返回null。您将需要调用createRow和/或createCell来创建单元格,您总是可以在该单元格上调用setCellStyle。
#2
0
cell.setCellStyle(sheet.getColumnStyle(index)
works well.
cell.setCellStyle(sheet.getColumnStyle(指数)的作品。
#1
6
If you have applied specific styles to an entire column, then you can retrieve that CellStyle
with Sheet
's getColumnStyle
method, passing it the 0-based column index. It retrieves a normal CellStyle
object that can be used anywhere else CellStyle
s are accepted, such as in Cell
's setCellStyle
method.
如果您对整个列应用了特定的样式,那么您可以使用Sheet的getColumnStyle方法检索该CellStyle,并将基于0的列索引传递给它。它检索一个普通的CellStyle对象,该对象可以在接受CellStyle的任何地方使用,比如在Cell的setCellStyle方法中。
For avoiding the NullPointerException
, both getRow
and getCell
may return null
if the row or cell doesn't exist, respectively. You will need to call createRow
and/or createCell
to create the Cell
, on which you can always call setCellStyle
.
为了避免NullPointerException,如果行或单元格不存在,getRow和getCell都可能返回null。您将需要调用createRow和/或createCell来创建单元格,您总是可以在该单元格上调用setCellStyle。
#2
0
cell.setCellStyle(sheet.getColumnStyle(index)
works well.
cell.setCellStyle(sheet.getColumnStyle(指数)的作品。