C#/VB.NET: Convert Excel Data to Word Tables with Formatting

2022-09-16 05:55:00 Written by  support iceblue
Rate this item
(0 votes)

If you're creating a written report on a company's monthly expenditures, you might need to include a spreadsheet to show the financial figures and make them easier to read. This article demonstrates how to convert Excel data into a Word table maintaining the formatting in C# and VB.NET using Spire.Office for .NET.

Install Spire.Office for .NET

To begin with, you need to add the DLL files included in the Spire.Office for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Office

Export Excel Data to a Word Table with Formatting

Below are the steps to convert Excel data to a Word table and keep the formatting using Spire.Office for .NET.

  • Create a Workbook object and load a sample Excel file using Workbook.LoadFromFile() method.
  • Get a specific worksheet through Workbook.Worksheets[index] property.
  • Create a Document object, and add a section to it.
  • Add a table using Section.AddTable() method.
  • Detect the merged cells in the worksheet and merge the corresponding cells of the Word tale using the custom method MergeCells().
  • Get value of a specific Excel cell through CellRange.Value property and add it to a cell of the Word table using TableCell.AddParagraph().AppendText() method.
  • Copy the font style and cell style from Excel to the Word table using the custom method CopyStyle().
  • Save the document to a Word file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Xls;

namespace ConvertExcelToWord
{
    internal class Program
    {
        static void Main(string[] args)
        {

            //Load an Excel file
            Workbook workbook = new Workbook();
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            //Create a Word document
            Document doc = new Document();
            Section section = doc.AddSection();
            section.PageSetup.Orientation = PageOrientation.Landscape;

            //Add a table
            Table table = section.AddTable(true);
            table.ResetCells(sheet.LastRow, sheet.LastColumn);

            //Merge cells
            MergeCells(sheet, table);

            for (int r = 1; r <= sheet.LastRow; r++)
            {
                //Set row Height
                table.Rows[r - 1].Height = (float)sheet.Rows[r - 1].RowHeight;

                for (int c = 1; c <= sheet.LastColumn; c++)
                {
                    CellRange xCell = sheet.Range[r, c];
                    TableCell wCell = table.Rows[r - 1].Cells[c - 1];

                    //Export data from Excel to Word table
                    TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);

                    //Copy font and cell style from Excel to Word
                    CopyStyle(textRange, xCell, wCell);
                }
            }

            //Save the document to a Word file
            doc.SaveToFile("ExportToWord.docx", Spire.Doc.FileFormat.Docx);
        }
        //Merge cells if any
        private static void MergeCells(Worksheet sheet, Table table)
        {
            if (sheet.HasMergedCells)
            {
                //Get merged cell ranges from Excel
                CellRange[] ranges = sheet.MergedCells;

                //Merge corresponding cells in Word table
                for (int i = 0; i < ranges.Length; i++)
                {
                    int startRow = ranges[i].Row;
                    int startColumn = ranges[i].Column;
                    int rowCount = ranges[i].RowCount;
                    int columnCount = ranges[i].ColumnCount;
                    if (rowCount > 1 && columnCount > 1)
                    {
                        for (int j = startRow; j <= startRow + rowCount; j++)
                        {
                            table.ApplyHorizontalMerge(j - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                        }
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                    }
                    if (rowCount > 1 && columnCount == 1)
                    {
                        table.ApplyVerticalMerge(startColumn - 1, startRow - 1, startRow - 1 + rowCount -1);
                    }
                    if (columnCount > 1 && rowCount == 1)
                    {
                        table.ApplyHorizontalMerge(startRow - 1, startColumn - 1, startColumn - 1 + columnCount - 1);
                    }
                }
            }
        }

        //Copy cell style of Excel to Word table
        private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
        {
            //Copy font style
            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;
            //Copy backcolor
            wCell.CellFormat.BackColor = xCell.Style.Color;
            //Copy horizontal alignment
            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;
            }
            //Copy vertical alignment
            switch (xCell.VerticalAlignment)
            {
                case VerticalAlignType.Bottom:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Bottom;
                    break;
                case VerticalAlignType.Center:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    break;
                case VerticalAlignType.Top:
                    wCell.CellFormat.VerticalAlignment = VerticalAlignment.Top;
                    break;
            }
        }
    }
}

C#/VB.NET: Convert Excel Data to Word Tables with Formatting

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Additional Info

  • tutorial_title:
Last modified on Monday, 19 September 2022 09:06