将 XSSF/HSSF-Cells 复制到新的 XSSFWorkbook [英] Copy a XSSF/HSSF-Cells into a new XSSFWorkbook
问题描述
我需要完全将单元格从XSSFWorkbook
s 和HSSFWorkbook
s 复制到新的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
包括 CellBorder
和 CellFill
属性以及工作簿本身的 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-Cells 复制到新的 XSSFWorkbook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!