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

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

问题描述

我需要完全将单元格从XSSFWorkbooks 和HSSFWorkbooks 复制到新的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.

正是,我的意思是我还需要复制 CellStyle 包括 CellBorderCellFill 属性以及工作簿本身的 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.

推荐答案

我的解决方案

我已经通过缩减需求解决了我的问题.现在我只专注于XSSFWorkbooks.

完全复制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-Cells 复制到新的 XSSFWorkbook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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