page 292

C#/VB.NET: Merge Excel Files into One

2012-03-19 06:55:53 Written by Koohji

Sometimes, we may get annoyed when we have to open many Excel files simultaneously. Merging Excel files of the same type or category can help us avoid the trouble and save us much time. This article will demonstrate how to merge Excel files into One in C# and VB.NET using Spire.XLS for .NET library.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS

Merge Multiple Excel Workbooks into One in C# and VB.NET

The following are the steps to merge multiple Excel workbooks into one:

  • Create a string array from the Excel file paths.
  • Initialize a Workbook object to create a new Excel workbook, and clear the default worksheets in the workbook using Workbook.Worksheets.Clear() method.
  • Initialize another temporary Workbook object.
  • Loop through the string array, load the current workbook into the temporary Workbook object using Workbook.LoadFromFile() method.
  • loop through the worksheets in the current workbook, then copy each worksheet from the current workbook to the new workbook using Workbook.Worksheets.AddCopy() method.
  • Save the new workbook to file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace MergeExcelFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a string array from Excel file paths
            string[] inputFiles = new string[] { "April.xlsx", "May.xlsx", "June.xlsx" };

            //Initialize a new Workbook object
            Workbook newWorkbook = new Workbook();
            //Clear the default worksheets
            newWorkbook.Worksheets.Clear();

            //Initialize another temporary Workbook object
            Workbook tempWorkbook = new Workbook();

            //Loop through the string array
            foreach (string file in inputFiles)
            {
                //Load the current workbook
                tempWorkbook.LoadFromFile(file);
                //Loop through the worksheets in the current workbook
                foreach (Worksheet sheet in tempWorkbook.Worksheets)
                {
                    //Copy each worksheet from the current workbook to the new workbook
                    newWorkbook.Worksheets.AddCopy(sheet, WorksheetCopyType.CopyAll);
                }
            }

            //Save the new workbook to file
            newWorkbook.SaveToFile("MergeWorkbooks.xlsx", ExcelVersion.Version2013);
        }
    }
}

The input Excel workbooks:

C#/VB.NET: Merge Excel Files into One

The merged Excel workbook:

C#/VB.NET: Merge Excel Files into One

Merge Multiple Excel Worksheets into One in C# and VB.NET

We can merge multiple worksheets in the same or different workbooks into one. The following steps show how to merge two Excel worksheets in the same workbook into a single worksheet:

  • Initialize a Workbook object and load an Excel file using Workbook.LoadFromFile() method.
  • Get the two worksheets that need to be merged using Workbook.Worksheets[sheetIndex] property. Note the sheet index is zero-based.
  • Get the used range of the second worksheet using Worksheet.AllocatedRange property.
  • Specify the destination range in the first worksheet using Worksheet.Range[rowIndex, columnIndex] property. Note the row and column indexes are 1-based.
  • Copy the used range of the second worksheet to the destination range in the first worksheet using CellRange.Copy(destRange) method.
  • Remove the second worksheet using XlsWorksheet.Remove() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace MergeExcelWorksheets
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook object
            Workbook workbook = new Workbook();
            //Load an Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet1 = workbook.Worksheets[0];
            //Get the second worksheet
            Worksheet sheet2 = workbook.Worksheets[1];

            //Get the used range in the second worksheet
            CellRange sourceRange = sheet2.AllocatedRange;
            //Specify the destination range in the first worksheet
            CellRange destRange = sheet1.Range[sheet1.LastRow + 1, 1];

            //Copy the used range of the second worksheet to the destination range in the first worksheet
            sourceRange.Copy(destRange);

            //Remove the second worksheet
            sheet2.Remove();

            //Save the result file
            workbook.SaveToFile("MergeWorksheets.xlsx", ExcelVersion.Version2013);
        }
    }
}

The input Excel worksheets:

C#/VB.NET: Merge Excel Files into One

The merged Excel worksheets:

C#/VB.NET: Merge Excel Files into One

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.

Merging cells means joining two or more separate cells into one large cell, which is useful when you need to create a label that spans multiple columns. In this article, we will demonstrate how to merge or unmerge cells in Excel in C# and VB.NET using Spire.XLS for .NET library.

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS 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.XLS

Merge Cells in Excel in C# and VB.NET

The following are the steps to merge cells in Excel:

  • C#
  • VB.NET
using Spire.Xls;

namespace MergeCells
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];
            //Merge cells A1-D1 into one cell
            CellRange range = sheet.Range["A1:D1"];
            range.Merge();
            //Center the text in the merged cell
            range.Style.HorizontalAlignment = HorizontalAlignType.Center;            

            //Save the result file
            workbook.SaveToFile("MergeCells.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Merge or Unmerge Cells in Excel

Unmerge Cells in Excel in C# and VB.NET

The following are the steps to unmerge cells in Excel:

  • C#
  • VB.NET
using Spire.Xls;

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

            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("MergeCells.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];
            //Unmerge cells A1-D1
            CellRange range = sheet.Range["A1:D1"];
            range.UnMerge();

            //Save the result file
            workbook.SaveToFile("UnMergeCells.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Merge or Unmerge Cells in Excel

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.

How to Set Word Table Column Width

2012-03-15 09:31:47 Written by Koohji

By using Spire.Doc, developers can create Word document with a table inside (Click to learn how to create table in Word document). But when users create table in Word document, they would not only create table with blank cells. They need set formats or sometimes set table size like column width. This article will show you how to set Word table column width.

Make sure Spire.Doc and Visual Studio are correctly installed on system. Follow the simple steps below to set Word table column width.

Step 1: Create a C# windows form application in Visual Studio. Add Spire.Doc.dll as reference. The default setting of Spire.Doc.dll is placed under "C:\Program Files\e-iceblue\Spire.Doc\Bin". Select assembly Spire.Doc.dll and click OK to add it to the project.

[C#]
using System;
using Spire.Doc;
using Spire.Doc.Fields;
using Spire.Doc.Documents;

namespace TableWidth
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Fields
Imports Spire.Doc.Documents

Namespace TableWidth
	Public Partial Class Form1
		Inherits Form
		Public Sub New()
			InitializeComponent()
		End Sub
		Private Sub button1_Click(sender As Object, e As EventArgs)
		End Sub
	End Class
End Namespace

Step 2: Put the word document with table into the project folder. Use the following code to load it into project.

[C#]
Document doc = new Document();
            doc.LoadFromFile(@"..\..\Table.docx",FileFormat.Docx);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("..\..\Table.docx", FileFormat.Docx)

Step 3: Because Spire.Doc doesn't have a direct method to set column width, we need set the first cell width of in each row.

[C#]
            for (int i = 0; i < document.Sections[0].Tables[0].Rows.Count; i++)
            {
                document.Sections[0].Tables[0].Rows[i].Cells[0].Width = 20;
            }
[VB.NET]
For i As Integer = 0 To document.Sections(0).Tables(0).Rows.Count - 1
	document.Sections(0).Tables(0).Rows(i).Cells(0).Width = 20
Next

Step 4: Save and Preview.

[C#]
document.SaveToFile(@"..\..\Sample.docx",FileFormat.Docx);
          
[VB.NET]
document.SaveToFile("..\..\Sample.docx", FileFormat.Docx)
System.Diagnostics.Process.Start("..\..\Test.pdf")

Now, the whole process is finished. Press F5 and click the button to run the project. The generated docx file can be found at the project debug folder. Check the effect.

Before Setting Width:

Word Table Column Width

After Setting Width:

Word Table Column Width

As a professional and powerful Word component, Spire.Doc doesn't need Microsoft Office Word Automation but also allows user to directly operate Word document, format and style and insert content to Word document.Click to learn more feature functions of Spire.Doc

page 292