Apache POI &颜色 [英] Apache POI & colors

查看:24
本文介绍了Apache POI &颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Apache POI 时遇到了一些问题,希望能得到一些帮助!!

I've some problems with Apache POI, some help would be nice!!

我想删除 Excel 工作表子部分中的颜色.为此,我尝试的第一件事是渲染我想要清理的单元格(假设仅第一行之一)并将它们的颜色设置为白色:

I would like to remove the colors in a subpart of an Excel sheet. To do so, the first thing I tried is to render the cells I want to clean (let say the one of the first row only) and to set their color to white:

cell.getCellStyle().setFillForegroundColor(IndexedColors.WHITE.index);

但如果我这样做,一些未渲染的单元格的颜色(比如第二行之一)也会更改为白色单元格.很奇怪,因为被改变的单元格的前景色不一样,所以我以为它们会有不同的风格......

But if i do that, the color of some cells that are not rendered (let say the one of the second row) are also changed to white cells. It's strange, because the cells that are changed do not have the same foreground color, so I thought they would have different styles ...

因此,我尝试了另一种方法:

Therefore, I've tried another way:

CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(IndexedColors.WHITE.index);
cell.setCellStyle(style);

这个想法是为了避免更改 Excel 工作表中不同单元格可能共有的样式.实际上,它解决了颜色问题,但是如果我这样做,我会在 Excel 表中丢失不同的样式,而我只想删除一些颜色...

The idea, is to avoid changing a style that may be common to different cells in the Excel sheet. Actually, it solves the color problem, but if I do that, I loose the different styles in the Excel sheet, while I only want to remove some colors...

我正在使用通用工作簿,并且正在阅读 xlsx(与 xls 相同的问题)你知道怎么做吗?多谢,问候,

I'm using a generic Workbook, and I'm reading a xlsx (same problem with a xls) Do you know how to do it ? Thx a lot, regards,

推荐答案

如果您想移除颜色,那么将填充图案更改为 NO_FILL 而不是将颜色设置为白色如下:

If you want to remove the colors, then probably it makes sense to change the fill pattern to NO_FILL rather than setting the color to white as follows:

style.setFillPattern(CellStyle.NO_FILL)

回到您的主要问题,您有两种处理单元格样式修正的选项:

Back to your main question, you've got 2 options of dealing with the cell style amendment:

  • 通过CellUtil.setCellStyleProperty方法修改样式

CellUtil.setCellStyleProperty(cell, workbook, CellUtil.FILL_PATTERN, CellStyle.NO_FILL)

  • 通过从现有样式克隆样式并修改属性

示例代码如下:

 CellStyle oldStyle = cell.getCellStyle();
 CellStyle newStyle = workbook.createCellStyle();
 newStyle.cloneStyleFrom(oldStyle);
 newStyle.setFillPattern(CellStyle.NO_FILL);
 cell.setCellStyle(newStyle);

然而,在第二种情况下,您将为每个单元格创建一个新的单元格样式,您可能会考虑重用一些已经更新的单元格样式并实现某种缓存(否则可能会导致性能问题和达到允许的样式限制).

However in the 2nd case you're going to create a new cell style for every cell and you might probably consider reusing some of the already updated cell styles and implementing some kind of caching (as otherwise it might lead to performance issues and reaching allowed styles limit).

这篇关于Apache POI &颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆