How to dynamically create excel file and save it to stream in your .NET applications?

This article reveals using Spire.XLS for .NET to create a new Excel file dynamically and save it to stream. Alternatively, loading Excel file from stream in C# will also be fully described in this article as an additional function of Spire.XLS for .NET.

First we need to complete the preparatory work:

  • Download the latest Spire.XLS and install it on your machine.
  • Add the Spire.XLS.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.

Here comes to the explanation of the code:

Dynamically create Excel file and save it to stream

Firstly you can initiate an object of Spire.XLS.workbook

Workbook wbToStream= new Workbook();

Add Spire.XlS.Worksheet object by using the WorkSheet properties of Spire.XlS.Workbook. After that, write text in cell by take advantage of Range properties of Worksheet.

Worksheet sheet = wbFromStream.Worksheets[0];
sheet.Range["C10"].Text = "The sample demonstrates how to save an Excel workbook to stream.";

Then call the method SaveToStream of the Spire.XLS.Workbook object and save all the data which is in XLS format to stream.

wbToStream.SaveToStream(file_stream);

Let’s preview the sample Excel:

save to stream

Load Excel file from stream in C#

You can initiate an object of Spire.Xls.Workbook

Workbook wbFromStream = new Workbook();

Load data which is in .xls format from steam by calling the method "LoadFromStream" of the Spire.XLS.Workbook object.

wbFromStream.LoadFromStream(fileStream);

Save the object of Spire.XLS.Workbook as an .xls file.

wbFromStream.SaveToFile("From_stream.xls");

Look at this screenshot:

save to stream

And what below is the full code used in the two functions:

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");
 fileStream.Dispose();
 System.Diagnostics.Process.Start("From_stream.xls");
}