Wednesday, 08 February 2012 03:08

Create Excel File in C#, VB.NET

This section is designed to provide developers a simple solution on how to create Excel file in C#, VB.NET via this .NET Excel component Spire.XLS for .NET.

Spire.XLS for .NET allows you to create Excel file on the formats of Excel (.xls) 97-2003 and Excel (.xlsx) 2007 and Excel(.xlsx)2010 without installing MS Excel or any third party library. Apart from creating Excel file, this Excel api also enables you to read, edit and manipulate Excel files with high efficiency in .NET applications.

Below is the sample code for you to find how you can create an Excel file:

[C#]
using Spire.Xls;
using System.IO;
namespace CreateExcelFiles
{
    class Program
    {

        static void Main(string[] args)
        {
            //A: Dynamically create Excel file and save it to stream
            Workbook wbToStream = new Workbook();
            Worksheet sheet = wbToStream.Worksheets[0];
            sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream.";
            FileStream file_stream = new FileStream("To_stream.xls", FileMode.Create);
            wbToStream.SaveToStream(file_stream);
            file_stream.Close();
            System.Diagnostics.Process.Start("To_stream.xls");

            //B. Load Excel file from stream
            Workbook wbFromStream = new Workbook();
            FileStream fileStream = File.OpenRead("sample.xls");
            fileStream.Seek(0, SeekOrigin.Begin);
            wbFromStream.LoadFromStream(fileStream);
            wbFromStream.SaveToFile("From_stream.xls", ExcelVersion.Version97to2003);
            fileStream.Dispose();
            System.Diagnostics.Process.Start("From_stream.xls");
        }

    }
}
[VB.NET]
Imports Spire.Xls
Imports System.IO
Namespace CreateExcelFiles
	Class Program

		Private Shared Sub Main(args As String())
			'A: Dynamically create Excel file and save it to stream
			Dim wbToStream As New Workbook()
			Dim sheet As Worksheet = wbToStream.Worksheets(0)
			sheet.Range("C10").Text = "The sample demonstrates how to save an Excel workbook to stream."
			Dim file_stream As New FileStream("To_stream.xls", FileMode.Create)
			wbToStream.SaveToStream(file_stream)
			file_stream.Close()
			System.Diagnostics.Process.Start("To_stream.xls")

			'B. Load Excel file from stream
			Dim wbFromStream As New Workbook()
			Dim fileStream As FileStream = File.OpenRead("sample.xls")
			fileStream.Seek(0, SeekOrigin.Begin)
			wbFromStream.LoadFromStream(fileStream)
			wbFromStream.SaveToFile("From_stream.xls", ExcelVersion.Version97to2003)
			fileStream.Dispose()
			System.Diagnostics.Process.Start("From_stream.xls")
		End Sub

	End Class
End Namespace

The Created Excel File

After executing above code, The Excel file is created and some string values are also added in the first Worksheet”Sheet1”. Please see the screenshot below:

Create Excel File

Published in Document Operation