合并和分割单元格

在工作表中合并单元格。

使用Microsoft Excel

以下是使用Microsoft Excel在工作表中合并单元格的步骤。

  1. 将要复制的数据复制到范围内左上角的单元格中。
  2. 选择要合并的单元格。
  3. 要合并行或列中的单元格并将单元格内容居中,点击合并和居中图标上的格式工具栏。

使用Aspose.Cells

Cells类具有一些有用的方法。例如,方法merge()将在指定的单元格范围内将单元格合并为一个单元格。

执行以下代码后生成以下输出。

已合并单元格(C6:E7)

todo:image_alt_text

代码示例

以下示例显示了如何在工作表中合并单元格(C6:E7)。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(MergingCellsInWorksheet.class) + "data/";
// Create a Workbook.
Workbook wbk = new Workbook();
// Create a Worksheet and get the first sheet.
Worksheet worksheet = wbk.getWorksheets().get(0);
// Create a Cells object to fetch all the cells.
Cells cells = worksheet.getCells();
// Merge some Cells (C6:E7) into a single C6 Cell.
cells.merge(5, 2, 2, 3);
// Input data into C6 Cell.
worksheet.getCells().get(5, 2).setValue("This is my value");
// Create a Style object to fetch the Style of C6 Cell.
Style style = worksheet.getCells().get(5, 2).getStyle();
// Create a Font object
Font font = style.getFont();
// Set the name.
font.setName("Times New Roman");
// Set the font size.
font.setSize(18);
// Set the font color
font.setColor(Color.getBlue());
// Bold the text
font.setBold(true);
// Make it italic
font.setItalic(true);
// Set the backgrond color of C6 Cell to Red
style.setForegroundColor(Color.getRed());
style.setPattern(BackgroundType.SOLID);
// Apply the Style to C6 Cell.
cells.get(5, 2).setStyle(style);
// Save the Workbook.
wbk.save(dataDir + "mergingcells_out.xls");
wbk.save(dataDir + "mergingcells_out.xlsx");
wbk.save(dataDir + "mergingcells_out.ods");
// Print message
System.out.println("Process completed successfully");

取消合并(拆分)合并的单元格

使用Microsoft Excel

以下是使用Microsoft Excel拆分合并单元格的步骤。

  1. 选择已合并的单元格。 当单元格已合并时,在格式工具栏上选择合并和居中
  2. 格式工具栏上点击合并和居中

使用Aspose.Cells

Cells类有一个名为unMerge()的方法,用于将单元格拆分为其原始状态。该方法使用合并单元格范围中的单元格引用来取消合并单元格。

代码示例

以下示例显示了如何拆分合并的单元格(C6)。该示例使用上一个示例中创建的文件,并拆分了合并的单元格。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(UnMergingCellsInWorksheet.class) + "data/";
// Create a Workbook.
Workbook wbk = new Workbook(dataDir + "mergingcells.xls");
// Create a Worksheet and get the first sheet.
Worksheet worksheet = wbk.getWorksheets().get(0);
// Create a Cells object to fetch all the cells.
Cells cells = worksheet.getCells();
// Unmerge the cells.
cells.unMerge(5, 2, 2, 3);
// Save the file.
wbk.save(dataDir + "UnMergingCellsInWorksheet_out.xls");
// Print message
System.out.println("Process completed successfully");

相关文章