Saturday, 17 August 2013 07:36

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

Written by  daisy zhang
Rate this item
(0 votes)

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:

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

Here comes to the explanation of the code.

A: Dynamically create Excel file and save it to stream

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

[C#]
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.

[C#]
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.

[C#]
wbToStream.SaveToStream(file_stream);

Let’s preview the sample Excel:

save to stream

B. Load Excel file from stream in C#.

You can initiate an object of Spire.Xls.Workbook

[C#]
Workbook wbFromStream = new Workbook();

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

[C#]
wbFromStream.LoadFromStream(fileStream);

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

[C#]
wbFromStream.SaveToFile("From_stream.xls");

Look at this screenshot:

save to stream

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

[C#]
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");
}

Additional Info

  • tutorial_title: Create Excel File and Save it to Stream
Last modified on Tuesday, 07 January 2014 09:54