How to: Save a Document to a File

  • 3 minutes to read

Important

The Workbook class is defined in the DevExpress.Docs.v21.2.dll assembly. Add this assembly to your project to use the Workbook API. You need an active license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this assembly in production code.

Use the Workbook.SaveDocument method to save a spreadsheet document. A DocumentFormat enumeration member specifies the document format.

Save to a File

// Add a reference to the DevExpress.Docs.dll assembly.
using DevExpress.Spreadsheet;
// ...

Workbook workbook = new Workbook();
// ...

// Save the modified document to the file.
workbook.SaveDocument("Documents\\SavedDocument.xlsx", DocumentFormat.Xlsx);

Save to a Stream

// Add a reference to the DevExpress.Docs.dll assembly. 
using DevExpress.Spreadsheet;
using System.IO;
// ...

Workbook workbook = new Workbook();
// ...

// Save the modified document to the stream.
using (FileStream stream = new FileStream("Documents\\SavedDocument.xlsx", 
    FileMode.Create, FileAccess.ReadWrite)) {
    workbook.SaveDocument(stream, DocumentFormat.Xlsx);
}

Asynchronous Save

Use the Workbook.SaveDocumentAsync method to asynchronously save a workbook to a file or stream.

Important

Take into account the following when you call this method:

  • The events fired by this method call may occur in a different thread than the target operation.

  • The operation is not thread safe (the document should not be accessed simultaneously by different threads). Wait until the operation is completed before you continue to work with the document (for example, use the await operator).

The following code sample shows how to merge two workbooks and save the result asynchronously.

private async void MergeWorkbooks()
{
  using (Workbook workbook1 = new Workbook())
  using (Workbook workbook2 = new Workbook())
  {
      await Task.WhenAll(new Task[]
      {
          workbook1.LoadDocumentAsync("book1.xlsx"),
          workbook2.LoadDocumentAsync("book2.xlsx")
      });
      workbook1.Append(workbook2);
      await workbook1.SaveDocumentAsync("merged.xlsx");
  }
}

Calculate Formulas Before Save Operation

The default calculation mode for a Workbook is Manual. This mode implies that the Spreadsheet component does not calculate formulas before it saves a document. Call the Workbook.Calculate or Workbook.CalculateFull method to calculate all formulas in the workbook.

using (Workbook workbook = new Workbook())
{
    // Load a document.
    // ...
    // Modify the document.
    // ...
    // Calculate formulas in the document.
    workbook.Calculate();
    // Save the document.
    workbook.SaveDocument("SavedDocument.xlsx", DocumentFormat.Xlsx);
}
See Also