LoginSignup
0
3

More than 5 years have passed since last update.

C#でWordにExcelテーブルをインポートする

Last updated at Posted at 2018-08-22

Word文書にExcelスプレッドシートを表示するには、Excel文書をOELオブジェクトとしてWordに挿入するか、Excel表をWordにコピーします。 この資料では、ExcelスプレッドシートをWordにコピーし、Excelの表のスタイルを保持する方法について説明します。
このシナリオでは、Spire.Xls.dllとSpire.Doc.dllの両方をプロジェクトで参照する必要があります。Spire.OfficeをダウンロードしてDLLファイルを使用してください。
【C#】

Program.cs

static void Main(string[] args)
{
//ワークブックオブジェクトを作成する
Workbook workbook = new Workbook();
//Excelドキュメントを読み込む
workbook.LoadFromFile(@"テスト.xlsx");
//最初のワークシートを取得する
Worksheet sheet = workbook.Worksheets[0];
//Documentオブジェクトを作成する
Document doc = new Document();
//Wordにフォームを追加する
Table table = doc.AddSection().AddTable(true);
//Excelテーブルデータの行数と列数に基づいてテーブルの行と列を設定する
table.ResetCells(sheet.LastRow, sheet.LastColumn);
//Excelテーブルの行をトラバースする
for (int r = 1; r <= sheet.LastRow; r++)
    {
     //Excelテーブルの列をトラバースする
     for (int c = 1; c <= sheet.LastColumn; c++)
         {
           //Excelテーブルのセルを取得する
           CellRange xCell = sheet.Range[r, c];
           //Wordの表のセルを取得する
           TableCell wCell = table.Rows[r - 1].Cells[c - 1];
           //Excelのセルデータを対応するWordセルに取り込みます
           TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);
                //セルフォーマットをコピーする
           CopyStyle(textRange, xCell, wCell);
           }
      }

       //ドキュメントを保存
       doc.SaveToFile("結果.docx", Spire.Doc.FileFormat.Docx);
    }
    private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
   {
    //フォントスタイルをコピーする
    wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
    wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
    wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
    wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
    wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
    //セルの背景色をコピーする
    wCell.CellFormat.BackColor = xCell.Style.Color;
    //テキストの配置をコピーする
    switch (xCell.HorizontalAlignment)
    {
        case HorizontalAlignType.Left:
            wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
            break;
        case HorizontalAlignType.Center:
            wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
            break;
        case HorizontalAlignType.Right:
            wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            break;
    }

}


デバッグコードが実行されると、ドキュメントという単語が生成されます
4.jpg

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3