チュートリアル

簡単にライブラリーを使用するためのチュートリアルコレクション

チュートリアル».NET»Spire.Doc for .NET»変換»C#/VB.NET:Word を Excel に変換する方法
2022-12-27

C#/VB.NET:Word を Excel に変換する方法

Word と Excel は全く異なるファイルタイプです。Word ドキュメントは、論文、手紙、またはレポートを書くために使用されます。Excel ドキュメントは、データを表形式で保存したり、グラフを作成したり、データを計算したりするために使用されます。通常、Excel は Word の元のレイアウトを表示するのが難しいため、複雑な Word ドキュメントを Excel スプレッドシートに変換することはお勧めしません。

ただし、Word ドキュメントが主に表から構成されており、Excel で表データを分析したい場合は、Spire.Office for .NET を使用して Word を Excel に変換できます。この方法により、ドキュメントの可読性を維持することもできます。

Spire.Office for .NET をインストールしますb

まず、Spire.Office for .NET パッケージに含まれている DLL ファイルを .NET プロジェクトの参照として追加する必要があります。DLL ファイルは、このリンクからダウンロードするか、NuGet を介してインストールできます。

b
PM> Install-Package Spire.Office

C# と VB.NET で Word を Excel に変換する

このシーンでは、実際に Spire.Office パッケージの2つのライブラリが使用されています。Spire.Doc for .NET は、Word ドキュメントからコンテンツを読み取り、抽出するために使用されます。Spire.XLS for .NET は、Excel ドキュメントを作成し、特定のセルにデータを書き込むために使用されます。このコード例を理解しやすくするために、次の3つのカスタム方法を作成して変換機能を実現しました。

  • ExportTableInExcel() - Word テーブルから指定した Excel セルにデータをエクスポートします。
  • CopyContentInTable() - Word のテーブルのセルから Excel セルにコンテンツをコピーします。
  • CopyTextAndStyle() - Word の段落から Excel セルに書式付きテキストをコピーします。

次の手順では、Spire.Office for .NET を使用して Word ドキュメント全体からワークシートにデータをエクスポートする方法を示します。

  • Document オブジェクトを作成し、Word ドキュメントをロードします。
  • Workbook オブジェクトを作成し、WordToExcel というワークシートを追加します。
  • ドキュメント内のすべてのセクションをループします。そして、セクションの下のすべてのドキュメントオブジェクトをループし、ドキュメントオブジェクトが段落またはテーブルであるかを決定します。
  • ドキュメントオブジェクトが段落の場合は、CopyTextAndStyle() メソッドを使用して、Excel の指定されたセルに段落を書き込みます。
  • ドキュメントオブジェクトがテーブルの場合は、ExportTableInExcel() メソッドを使用してテーブルのデータを Word から Excel セルにエクスポートします。
  • Excel で行の高さと列の幅を自動的に調整し、セルのデータがセルの限界を超えないようにします。
  • Workbook.SaveToFile() メソッドを使用して、ブック を Excel に保存します。
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;
using System;
using System.Drawing;

namespace ConvertWordToExcel
{
    class Program
    {
        static void Main(string[] args)
        {
            //Documentオブジェクトを作成する
            Document doc = new Document();

            //Wordサンプル・ドキュメントをロードする
            doc.LoadFromFile(@"sample.docx");

            //Workbookオブジェクトを作成する
            Workbook wb = new Workbook();

            //デフォルト・ワークシートを削除する
            wb.Worksheets.Clear();

            //「WordToExcel」というワークシートを作成する
            Worksheet worksheet = wb.CreateEmptySheet("WordToExcel");
            int row = 1;
            int column = 1;

            //Wordドキュメントのセクションをループする
            foreach (Section section in doc.Sections)
            {
                //セクション内のドキュメントオブジェクトをループする
                foreach (DocumentObject documentObject in section.Body.ChildObjects)
                {
                    //オブジェクトが段落かどうかを判断する
                    if (documentObject is Paragraph)
                    {
                        CellRange cell = worksheet.Range[row, column];
                        Paragraph paragraph = documentObject as Paragraph;
                        //Wordの段落を特定のセルにコピーする
                        CopyTextAndStyle(cell, paragraph);
                        row++;
                    }

                    //オブジェクトがテーブルかどうかを判断する
                    if (documentObject is Table)
                    {
                        Table table = documentObject as Table;
                        //テーブルのデータをWordからExcelにエクスポートする
                        int currentRow = ExportTableInExcel(worksheet, row, table);
                        row = currentRow;
                    }
                }
            }

            //行の高さと列の幅を自動調整する
            worksheet.AllocatedRange.AutoFitRows();
            worksheet.AllocatedRange.AutoFitColumns();

            //テキストをセルでラップする
            worksheet.AllocatedRange.IsWrapText = true;

            //ワークブックをExcelに保存する
            wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013);
        }

        //WordのテーブルからExcelセルにデータをエクスポートする
        private static int ExportTableInExcel(Worksheet worksheet, int row, Table table)
        {
            CellRange cell;
            int column;
            foreach (TableRow tbRow in table.Rows)
            {
                column = 1;
                foreach (TableCell tbCell in tbRow.Cells)
                {
                    cell = worksheet.Range[row, column];
                    cell.BorderAround(LineStyleType.Thin, Color.Black);
                    CopyContentInTable(tbCell, cell);
                    column++;
                }
                row++;
            }
            return row;
        }

        //WordテーブルのセルからExcelのセルにコンテンツをコピーする
        private static void CopyContentInTable(TableCell tbCell, CellRange cell)
        {
            Paragraph newPara = new Paragraph(tbCell.Document);
            for (int i = 0; i < tbCell.ChildObjects.Count; i++)
            {
                DocumentObject documentObject = tbCell.ChildObjects[i];
                if (documentObject is Paragraph)
                {
                    Paragraph paragraph = documentObject as Paragraph;
                    foreach (DocumentObject cObj in paragraph.ChildObjects)
                    {
                        newPara.ChildObjects.Add(cObj.Clone());
                    }
                    if (i < tbCell.ChildObjects.Count - 1)
                    {
                        newPara.AppendText("\n");
                    }
                }
            }
            CopyTextAndStyle(cell, newPara);
        }

        //段落のテキストとスタイルをセルにコピーする
        private static void CopyTextAndStyle(CellRange cell, Paragraph paragraph)
        {
            RichText richText = cell.RichText;
            richText.Text = paragraph.Text;
            int startIndex = 0;
            foreach (DocumentObject documentObject in paragraph.ChildObjects)
            {
                if (documentObject is TextRange)
                {
                    TextRange textRange = documentObject as TextRange;
                    string fontName = textRange.CharacterFormat.FontName;
                    bool isBold = textRange.CharacterFormat.Bold;
                    Color textColor = textRange.CharacterFormat.TextColor;
                    float fontSize = textRange.CharacterFormat.FontSize;
                    string textRangeText = textRange.Text;
                    int strLength = textRangeText.Length;
                    ExcelFont font = cell.Worksheet.Workbook.CreateFont();
                    font.Color = textColor;
                    font.IsBold = isBold;
                    font.Size = fontSize;
                    font.FontName = fontName;
                    int endIndex = startIndex + strLength;
                    richText.SetFont(startIndex, endIndex, font);
                    startIndex += strLength;
                }
                if (documentObject is DocPicture)
                {
                    DocPicture picture = documentObject as DocPicture;
                    cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image);
                    cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height);
                }
            }
            switch (paragraph.Format.HorizontalAlignment)
            {
                case HorizontalAlignment.Left:
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Left;
                    break;
                case HorizontalAlignment.Center:
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Center;
                    break;
                case HorizontalAlignment.Right:
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Right;
                    break;
            }
        }
    }
}
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Xls
Imports System
Imports System.Drawing
 
Namespace ConvertWordToExcel
    Class Program
        Shared  Sub Main(ByVal args() As String)
            'Documentオブジェクトを作成する
            Document doc  =  New Document()
 
            'Wordサンプル・ドキュメントをロードする
            doc.LoadFromFile("sample.docx")
 
            'Workbookオブジェクトを作成する
            Dim wb As Workbook =  New Workbook() 
 
            'デフォルト・ワークシートを削除する
            wb.Worksheets.Clear()
 
            '「WordToExcel」というワークシートを作成する
            Dim worksheet As Worksheet =  wb.CreateEmptySheet("WordToExcel") 
            Dim row As Integer =  1 
            Dim column As Integer =  1 
 
            'Wordドキュメントのセクションをループする
            Dim section As Section
            For Each section In doc.Sections
                'セクション内のドキュメントオブジェクトをループする
                Dim documentObject As DocumentObject
                For Each documentObject In section.Body.ChildObjects
                    'オブジェクトが段落かどうかを判断する
                    If TypeOf documentObject Is Paragraph Then
                        Dim cell As CellRange =  worksheet.Range(row,column) 
                        Dim paragraph As Paragraph =  documentObject as Paragraph 
                        'Wordの段落を特定のセルにコピーする
                        CopyTextAndStyle(cell, paragraph)
                        row = row + 1
                    End If
 
                    'オブジェクトがテーブルかどうかを判断する
                    If TypeOf documentObject Is Table Then
                        Dim table As Table =  documentObject as Table 
                        'テーブルのデータをWordからExcelにエクスポートする
                        Dim currentRow As Integer =  ExportTableInExcel(worksheet,row,table) 
                        row = currentRow
                    End If
                Next
            Next
 
            '行の高さと列の幅を自動調整する
            worksheet.AllocatedRange.AutoFitRows()
            worksheet.AllocatedRange.AutoFitColumns()
 
            'テキストをセルでラップする
            worksheet.AllocatedRange.IsWrapText = True
 
            'ワークブックをExcelに保存する
            wb.SaveToFile("WordToExcel.xlsx", ExcelVersion.Version2013)
        End Sub
 
        'WordのテーブルからExcelセルにデータをエクスポートする
        Private Shared Function ExportTableInExcel(ByVal worksheet As Worksheet, ByVal row As Integer, ByVal table As Table) As Integer
            Dim cell As CellRange
            Dim column As Integer
            Dim tbRow As TableRow
            For Each tbRow In table.Rows
                column = 1
                Dim tbCell As TableCell
                For Each tbCell In tbRow.Cells
                    cell = worksheet.Range(row, column)
                    cell.BorderAround(LineStyleType.Thin, Color.Black)
                    CopyContentInTable(tbCell, cell)
                    column = column + 1
                Next
                row = row + 1
            Next
            Return row
        End Function
 
        'WordテーブルのセルからExcelのセルにコンテンツをコピーする
        Private Shared  Sub CopyContentInTable(ByVal tbCell As TableCell, ByVal cell As CellRange)
            Dim NewPara As Paragraph =  New Paragraph(tbCell.Document) 
            Dim i As Integer
            For  i = 0 To  tbCell.ChildObjects.Count- 1  Step  i + 1
                Dim documentObject As DocumentObject =  tbCell.ChildObjects(i) 
                If TypeOf documentObject Is Paragraph Then
                    Dim paragraph As Paragraph =  documentObject as Paragraph 
                    Dim cObj As DocumentObject
                    For Each cObj In paragraph.ChildObjects
                        NewPara.ChildObjects.Add(cObj.Clone())
                    Next
                    If i < tbCell.ChildObjects.Count - 1 Then
                        NewPara.AppendText("\n")
                    End If
                End If
            Next
            CopyTextAndStyle(cell, NewPara)
        End Sub
 
        '段落のテキストとスタイルをセルにコピーする
        Private Shared  Sub CopyTextAndStyle(ByVal cell As CellRange, ByVal paragraph As Paragraph)
            Dim richText As RichText =  cell.RichText 
            richText.Text = paragraph.Text
            Dim startIndex As Integer =  0 
            Dim documentObject As DocumentObject
            For Each documentObject In paragraph.ChildObjects
                If TypeOf documentObject Is TextRange Then
                    Dim textRange As TextRange =  documentObject as TextRange 
                    Dim fontName As String =  textRange.CharacterFormat.FontName 
                    Dim isBold As Boolean =  textRange.CharacterFormat.Bold 
                    Dim textColor As Color =  textRange.CharacterFormat.TextColor 
                    Dim fontSize As single =  textRange.CharacterFormat.FontSize 
                    Dim textRangeText As String =  textRange.Text 
                    Dim strLength As Integer =  textRangeText.Length 
                    Dim font As ExcelFont =  cell.Worksheet.Workbook.CreateFont() 
                    font.Color = textColor
                    font.IsBold = isBold
                    font.Size = fontSize
                    font.FontName = fontName
                    Dim endIndex As Integer =  startIndex + strLength 
                    richText.SetFont(startIndex, endIndex, font)
                    startIndex += strLength
                End If
                If TypeOf documentObject Is DocPicture Then
                    Dim picture As DocPicture =  documentObject as DocPicture 
                    cell.Worksheet.Pictures.Add(cell.Row, cell.Column, picture.Image)
                    cell.Worksheet.SetRowHeightInPixels(cell.Row, 1, picture.Image.Height)
                End If
            Next
            Select Case paragraph.Format.HorizontalAlignment
                Case HorizontalAlignment.Left
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Left
                    Exit For
                Case HorizontalAlignment.Center
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Center
                    Exit For
                Case HorizontalAlignment.Right
                    cell.Style.HorizontalAlignment = HorizontalAlignType.Right
                    Exit For
            End Select
        End Sub
    End Class
End Namespace

C#/VB.NET:Word を Excel に変換する方法

一時ライセンスを申請する

結果ドキュメントから評価メッセージを削除したい場合、または機能制限を取り除く場合は、についてこのメールアドレスはスパムボットから保護されています。閲覧するにはJavaScriptを有効にする必要があります。にお問い合わせ、30 日間有効な一時ライセンスを取得してください。

Read 486 times