2 回答
TA貢獻1796條經(jīng)驗 獲得超4個贊
合并的單元格區(qū)域將它們定向到該區(qū)域中的第一個單元格。這意味著單元格樣式以及單元格值。所以首先需要設置第一個單元格的單元格樣式來換行。然后我們需要將所有單元格值連接到第一個單元格的單元格值中,該單元格值由換行符“\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();
}
}
SAMPLENEW.xlsx:

我concatenateAndMerge使用DataFormatter的方法是因為源單元格內容可能不僅僅是文本,而是日期或其他數(shù)字。由于合并的單元格內容需要是串聯(lián)字符串,因此之前單個單元格的不同內容應該出現(xiàn)在該串聯(lián)字符串中,如之前在單個單元格中所示。這就是為什么DataFormatter. 我的方法使用FormulaEvaluator是因為源單元格內容也可能包含公式。
TA貢獻1830條經(jīng)驗 獲得超3個贊
如果直接在 excel 中使用 VBA 是一種可行的替代方案,您可以編寫一個宏來完成此任務。宏將保存在實際的 excel 文件中。
當 Excel 合并單元格時,它只保留第一個單元格的值,因此在合并這些單元格之前,請以您想要的格式連接它們的值。要為您的值添加換行符,請Chr(10)在您想要新行的位置連接。
請記住,如果您以這種方式格式化數(shù)字單元格,則單元格值將變?yōu)樽址虼瞬荒茉儆米鞴街械臄?shù)字。
以下代碼將執(zhí)行您想要的*:
Dim finalValue As String
For Each c In Selection
finalValue = finalValue & IIf((Len(finalValue) > 0) And (Len(c.Text) > 0), Chr(10), Empty) & c.Text
Next c
Selection.Clear
Selection.Merge
Selection.Value = finalValue
*注意:如果您需要對可變單元格編號執(zhí)行此任務,我選擇了代碼,但它適用于任何Range對象
另請注意,除非您刪除And (Len(c.Text) > 0). IIf但是通過這樣做,將選擇與已合并的單元格合并將創(chuàng)建盡可能多的空行[the size of the merged cell] - 1
添加回答
舉報
