C# Logo

C# Save to Stream or Byte Array SpreadsheetGear API Sample

Excel-Compatible Samples for .NET

Description

In addition to saving to disk using the SpreadsheetGear.IWorkbook.SaveAs(...) and Save() methods, SpreadsheetGear can save to a memory stream using the IWorkbook.SaveToStream(SpreadsheetGear.FileFormat fileFormat) method; or to a byte array using the IWorkbook.SaveToMemory(SpreadsheetGear.FileFormat fileFormat) method.

Password-Protected and Encrypted Files

Tip: overloads of these methods are available if you need to password protect and encrypt the workbook. Just pass in a second "password" parameter:
  • System.IO.Stream stream = SpreadsheetGear.IWorkbook.SaveToStream(SpreadsheetGear.FileFormat, string password);
  • byte[] bytes = SpreadsheetGear.IWorkbook.SaveToMemory(SpreadsheetGear.FileFormat, string password);

Sample C# Source Code

// Create a new workbook and some local variables for convenience.
SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();
SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets["Sheet1"];
SpreadsheetGear.IRange cells = worksheet.Cells;

// Rename the worksheet.
worksheet.Name = "My Worksheet";

// Add some cell data.
cells["A1"].Value = "Hello World!";

// Save to stream.
System.IO.Stream stream = workbook.SaveToStream(SpreadsheetGear.FileFormat.OpenXMLWorkbook);

// Or save to byte array.
byte[] bytes = workbook.SaveToMemory(SpreadsheetGear.FileFormat.OpenXMLWorkbook);