C# を使用して Word でセルを結合する

この短いチュートリアルでは、C# を使用して Word のセルを結合する 方法について説明します。IDE を設定するための詳細、手順の一覧、セルを結合するための定義済み関数、およびこの定義済み関数を使用して C# を使用して Word で表を結合する方法 を示すサンプル コードが含まれています。このタスクを実行するために、他のサードパーティ ツールは必要ありません。

C# を使用して Word の表のセルを結合する手順

  1. IDE で Aspose.Words for .NET を使用して表内のセルを結合するように設定します
  2. アプリケーションで使用するために定義済みメソッド MergeCells を宣言します。
  3. 1 つ以上の表を含む Document オブジェクトにソース Word ファイルを読み込みます。
  4. 読み込まれたWordファイル内の表にアクセスしてセルを結合する
  5. ターゲットマージ範囲の開始 cell にアクセスします
  6. 結合範囲の終了セルにアクセスする
  7. 開始セルと終了セルを指定してMergeCells()メソッドを呼び出し、ドキュメントを保存します。

これらの手順は、C# を使用して Word でセルを結合する方法 に役立ちます。プロジェクトに定義済みメソッドを追加し、結合する開始セルと終了セルを指定して呼び出します。ソース ファイルが変更されるため、読み込まれた Word ファイルを結合されたセルを含む別の名前で保存できます。

C# を使用して Word のセルを結合するコード

using System;
using System.Drawing;
using Aspose.Words;
using Aspose.Words.Tables;
class Program
{
static void MergeCells(Cell startCell, Cell endCell)
{
Table parentTable = startCell.ParentRow.ParentTable;
// Find the start and end cell
Point startingCell = new Point(startCell.ParentRow.IndexOf(startCell), parentTable.IndexOf(startCell.ParentRow));
Point endingCell = new Point(endCell.ParentRow.IndexOf(endCell), parentTable.IndexOf(endCell.ParentRow));
// Create a range of cells
Rectangle mergeRange = new Rectangle(Math.Min(startingCell.X, endingCell.X),Math.Min(startingCell.Y, endingCell.Y),
Math.Abs(endingCell.X - startingCell.X) + 1, Math.Abs(endingCell.Y - startingCell.Y) + 1);
foreach (Row currentRow in parentTable.Rows)
{
foreach (Cell currentCell in currentRow.Cells)
{
Point currentPos = new Point(currentRow.IndexOf(currentCell), parentTable.IndexOf(currentRow));
// Check if the current cell is inside the range
if (mergeRange.Contains(currentPos))
{
currentCell.CellFormat.HorizontalMerge = currentPos.X == mergeRange.X ? CellMerge.First : CellMerge.Previous;
currentCell.CellFormat.VerticalMerge = currentPos.Y == mergeRange.Y ? CellMerge.First : CellMerge.Previous;
}
}
}
}
static void Main(string[] args)
{
License lic = new License();
lic.SetLicense("license.lic");
Document doc = new Document("Table.docx");
Table table = doc.FirstSection.Body.Tables[0];
// Define starting and ending cells
Cell cellStartRange = table.Rows[0].Cells[0];
Cell cellEndRange = table.Rows[1].Cells[1];
// Merge all the cells
MergeCells(cellStartRange, cellEndRange);
doc.Save("Output.docx");
}
}

このコードは、C# を使用して Word で表を結合する方法 を示しています。定義済みのメソッド MergeCells とその定義を追加し、必要に応じてアプリケーションで呼び出します。セクション、そのセクション内の表のリストを選択し、インデックスを使用してターゲット表にアクセスし、結合の開始セルと終了セルを選択できます。このプロセスを繰り返して、必要な数のセルを結合できます。

C# を使用して Microsoft Word でセルを結合する方法 を学習しました。Word 文書全体を結合する場合は、C# を使用して Word 文書を結合する方法 の記事を参照してください。

 日本語