将XSSF/HSSF单元复制到新的XSSFWorkbook中 [英] Copy a XSSF/HSSF-Cells into a new XSSFWorkbook
问题描述
我需要完全将单元格从XSSFWorkbook
和HSSFWorkbook
复制到新的XSSFWorkbook
.所以我的细胞可以是两种类型:XSSFCell
和HSSFCell
.
I need to exactly copy cells from XSSFWorkbook
s and HSSFWorkbook
s to a new XSSFWorkbook
. So my cells can be of both types: XSSFCell
and HSSFCell
.
确切地说,我是说我还需要复制包含工作簿本身的CellStyle
和CellFill
属性的CellStyle
以及工作簿本身的DefaultRowHeight
和DefaultColumnWidth
.此外,还应复制每一行和每一列的高度和宽度.
(复制CellStyle
有时会导致奇怪的行为,例如我已经问过
By exactly, I mean that I also need to copy the CellStyle
including the CellBorder
and CellFill
properties as well as the DefaultRowHeight
and DefaultColumnWidth
of the workbook itself. Also the height and width for each row and column should be copied.
(Copying CellStyle
sometimes results in strange behaviour like I already asked here).
执行此操作的最佳方法是什么?我不想自己手动复制每个属性.尤其是如果我不知道我的输入单元格是XSSFCell
还是HSSFCell
类型.
What's the best way to do this? I don't want to copy each property manually by myself. Especially if I don't know if my input cells are of type XSSFCell
or HSSFCell
.
推荐答案
我的解决方案
我已经通过缩减需求解决了我的问题.现在我只专注于XSSFWorkbook
s.
精确复制XSSFWorkbook
非常容易.要将XSSFCellStyle
复制到另一个工作簿,只需使用以下代码:
Exactly copying a XSSFWorkbook
is really easy. To copy a XSSFCellStyle
to another workbook just use the following code:
// Copy cell style from `sourceCell` to `targetCell`
XSSFCellStyle sourceCellStyle = sourceCell.getCellStyle();
XSSFCellStyle clonedCellStyle = newWorkbook.createCellStyle();
clonedCellStyle.cloneStyleFrom(sourceCellStyle);
targetCell.setCellStyle(clonedCellStyle);
重要的是目标工作簿应具有与源工作簿相同的样式源.否则,克隆的单元格样式将看起来有所不同.
It's important that the target workbook has the same style source as the source workbook. Otherwise the cloned cell style will look differently.
final StylesTable sourceStylesSource = sourceWorkbook.getStylesSource();
final StylesTable tagetStylesSource = targetWorkbook.getStylesSource();
sourceStylesSource.getFonts().forEach(font -> targetStylesSource.putFont(font, true));
sourceStylesSource.getFills().forEach(fill -> targetStylesSource.putFill(new XSSFCellFill(fill.getCTFill())));
sourceStylesSource.getBorders().forEach(border -> targetStylesSource.putBorder(new XSSFCellBorder(border.getCTBorder())));
我希望这对某人有帮助!
问候,winklerrr
I hope this helps someone!
Regards, winklerrr
如果某人无法缩减需求,那么将任务分解为两个较小的任务可能会有所帮助:
If someone can't downscale the requirements, then maybe it's helpful to split up the task into two smaller tasks:
- 将
HSSFWorkbook
转换为XSSFWorkbook
,反之亦然. - 精确复制
XSSFWorkbook
.
- Convert a
HSSFWorkbook
to aXSSFWorkbook
and vice versa. - Copy a
XSSFWorkbook
exactly.
这篇关于将XSSF/HSSF单元复制到新的XSSFWorkbook中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!