垂直合并单元格并将数据插入单元格

El *_*cuy 3 java excel apache-poi

我的问题是我有 4 个价值观。我需要在一个单元格中表示它们。

我需要垂直合并单元格(列),并在另一个值下方(从上到下)显示四个值,并在合并的单元格之间有换行符。

我可以垂直合并单元格,但无法在单个单元格中呈现四个值。

CellRangeAddress cellRangeAddress = new CellRangeAddress(2,5,5,5);
sheet.addMergedRegion(cellRangeAddress);
Run Code Online (Sandbox Code Playgroud)

Axe*_*ter 5

合并的单元格区域将它们自身定向到该区域中的第一个单元格。这意味着单元格样式和单元格值。因此需要首先设置第一个单元格的单元格样式以换行文本。然后,我们需要将所有单元格值连接在一起,形成第一个单元格的单元格值,并以“\n”(换行符)分隔。然后我们可以合并单元格。

例子:

示例.xlsx: 在此输入图像描述

代码:

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.util.LocaleUtil;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Locale;

class ExcelConcatenateAndMerge {

 private static void concatenateAndMerge(
  Sheet sheet, CellRangeAddress cellRangeAddress, DataFormatter formatter, FormulaEvaluator evaluator, CellStyle cellStyle) {

  Row row = null;
  Cell cell = null;
  Cell firstCell = null;
  String cellValue = "";
  boolean first = true;
  for (CellAddress cellAddress : cellRangeAddress) {
   row = sheet.getRow(cellAddress.getRow());
   if (first) {
    if (row == null) row = sheet.createRow(cellAddress.getRow());
    firstCell = row.getCell(cellAddress.getColumn());
    if (firstCell == null) firstCell = row.createCell(cellAddress.getColumn());
    firstCell.setCellStyle(cellStyle);
    cellValue = formatter.formatCellValue(firstCell, evaluator);
    first = false;
   } else {
    if (row != null) {
     cell = row.getCell(cellAddress.getColumn());
     if (cell != null) {
      cellValue += "\n" + formatter.formatCellValue(cell, evaluator);
     } else cellValue += "\n" + "";
    } else cellValue += "\n" + "";
   }
  }

  firstCell.setCellValue(cellValue);

  sheet.addMergedRegion(cellRangeAddress);

 }

 public static void main(String[] args) throws Exception {

  Workbook wb  = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));

  Locale locale = new Locale("en", "US");
  LocaleUtil.setUserLocale(locale);
  DataFormatter formatter = new DataFormatter();
  FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
  CellStyle cellStyle = wb.createCellStyle();
  cellStyle.setWrapText(true);

  Sheet sheet = wb.getSheetAt(0);
  CellRangeAddress cellRangeAddress = new CellRangeAddress(2,5,5,5);

  concatenateAndMerge(sheet, cellRangeAddress, formatter, evaluator, cellStyle);

  FileOutputStream out = new FileOutputStream("SAMPLENEW.xlsx");
  wb.write(out);
  out.close();
  wb.close();

 }
}
Run Code Online (Sandbox Code Playgroud)

样本新.xlsx: 在此输入图像描述

我的方法之所以concatenateAndMerge使用DataFormatter,是因为源单元格内容可能不仅仅是文本,而是日期或其他数字。由于合并的单元格内容需要是一个连接字符串,因此先前单个单元格的不同内容应出现在该连接字符串中,如之前在单个单元格中所示。这就是为什么DataFormatter. 我的方法使用是FormulaEvaluator因为源单元格内容也可能包含公式。