将XSSF/HSSF单元复制到新的XSSFWorkbook中 [英] Copy a XSSF/HSSF-Cells into a new XSSFWorkbook

查看:809
本文介绍了将XSSF/HSSF单元复制到新的XSSFWorkbook中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要完全将单元格从XSSFWorkbookHSSFWorkbook复制到新的XSSFWorkbook.所以我的细胞可以是两种类型:XSSFCellHSSFCell.

I need to exactly copy cells from XSSFWorkbooks and HSSFWorkbooks to a new XSSFWorkbook. So my cells can be of both types: XSSFCell and HSSFCell.

确切地说,我是说我还需要复制包含工作簿本身的CellStyleCellFill属性的CellStyle以及工作簿本身的DefaultRowHeightDefaultColumnWidth .此外,还应复制每一行和每一列的高度和宽度. (复制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:

  1. HSSFWorkbook转换为XSSFWorkbook,反之亦然.
  2. 精确复制XSSFWorkbook.
  1. Convert a HSSFWorkbook to a XSSFWorkbook and vice versa.
  2. Copy a XSSFWorkbook exactly.

这篇关于将XSSF/HSSF单元复制到新的XSSFWorkbook中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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