java Apache POI 保留现有的 Excel 格式样式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12373251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Apache POI preserve existing Excel formatting style
提问by JavaKungFu
I'm using Apache POI to read an existing template excel file and would like to copy the existing styles in some header rows and apply them to new cells.
我正在使用 Apache POI 读取现有模板 excel 文件,并希望复制某些标题行中的现有样式并将它们应用于新单元格。
It seems like the existing formatting is not being applied (IE, Date, Currency, Percentage etc).
似乎没有应用现有的格式(IE、日期、货币、百分比等)。
The code is pretty basic:
代码非常基本:
//read existing style
Row existingRow = sheet.getRow(headerRowIndex);
Cell existingCell = existingRow.getCell(0);
CellStyle currentStyle = existingCell.getCellStyle();
//apply date style here
Date date = StringUtil.toDate(map.get(column.getHeaderName()));
cell.setCellValue(date);
//apply previous style
cell.setCellStyle(currentStyle);
It does copy the font and background color etc but it seems like the formatting is lost (all cells have "general" formatting applied).
它确实复制了字体和背景颜色等,但似乎格式丢失了(所有单元格都应用了“常规”格式)。
Also when I do this:
当我这样做时:
currentStyle.getDataFormat(); // always 0
So it makes me think that I'm not reading the formatting correctly. Any ideas on how to accomplish this?
所以这让我觉得我没有正确阅读格式。关于如何实现这一点的任何想法?
采纳答案by JavaKungFu
OK I figured it out, it was my mistake. I was reading the style from the first cell in the row and applying it to all, instead of reading from each cell.
好吧,我想通了,这是我的错误。我正在从行中的第一个单元格读取样式并将其应用于所有单元格,而不是从每个单元格中读取。
This fixes it
这修复了它
Cell existingCell = existingRow.getCell(i);