Back to Devexpress

Workbook.LoadDocumentAsync(Stream, DocumentFormat, CancellationToken, IProgress<Int32>) Method

officefileapi-devexpress-dot-spreadsheet-dot-workbook-dot-loaddocumentasync-x28-system-dot-io-dot-stream-devexpress-dot-spreadsheet-dot-documentformat-system-dot-threading-dot-cancellationtoken-system-dot-iprogress-system-dot-int32-x29.md

latest10.4 KB
Original Source

Workbook.LoadDocumentAsync(Stream, DocumentFormat, CancellationToken, IProgress<Int32>) Method

SECURITY-RELATED CONSIDERATIONS

Downloading documents passed into the LoadDocument method may create security issues. Review the following help topic and learn how to spot, analyze, and prohibit unwanted download requests:

Suppress Control Requests to Download Data from External URLs

Asynchronously loads a document in the specified format from a stream. Allows you to implement progress notifications and cancel the operation.

You need a license for the DevExpress Office File API Subscription or DevExpress Universal Subscription to use this method in production code.

Namespace : DevExpress.Spreadsheet

Assembly : DevExpress.Docs.v25.2.dll

NuGet Package : DevExpress.Document.Processor

Declaration

csharp
public Task<bool> LoadDocumentAsync(
    Stream stream,
    DocumentFormat format,
    CancellationToken cancellationToken,
    IProgress<int> progress
)
vb
Public Function LoadDocumentAsync(
    stream As Stream,
    format As DocumentFormat,
    cancellationToken As CancellationToken,
    progress As IProgress(Of Integer)
) As Task(Of Boolean)

Parameters

NameTypeDescription
streamStream

A stream that contains document data.

| | format | DocumentFormat |

An enumeration member that specifies the format of the loaded document.

| | cancellationToken | CancellationToken |

A cancellation token that indicates whether to cancel the operation.

| | progress | IProgress<Int32> |

An object used to report the task progress in percentage. Use a Progress<T> class instance to report progress.

|

Returns

TypeDescription
Task<Boolean>

A task that returns true if the document was loaded successfully; otherwise, false.

|

Remarks

If you attempt to load a document in an incorrect format, the Workbook.InvalidFormatException event fires. To throw an exception when an invalid document is loaded, set the Workbook.Options.Import.ThrowExceptionOnInvalidDocument property to true.

Handle the Workbook.DocumentLoaded event to determine when you can safely modify the loaded document.

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).

Example: Report Progress of Workbook Operations

The following example asynchronously loads and exports a workbook to PDF. The console window displays the progress of each operation. If the load or export operation takes longer than 30 seconds, it is canceled.

csharp
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using DevExpress.Spreadsheet;
using DevExpress.XtraPrinting;
// ...

static async Task Main(string[] args) {
    var cancellationSource = new CancellationTokenSource(TimeSpan.FromSeconds(30));
    var cancellationToken = cancellationSource.Token;
    try {
        using (Workbook workbook = new Workbook()) {
            Console.WriteLine("Loading a document...");
            using (FileStream docStream = new FileStream("Document.xlsx", FileMode.Open))
            {
                await workbook.LoadDocumentAsync(docStream, DocumentFormat.Xlsx,
                cancellationToken,
                new Progress<int>((progress) => Console.WriteLine($"{progress}%")));
            }
            Console.WriteLine("Exporting to PDF...");
            // Specify PDF export options.
            var pdfOptions = new PdfExportOptions()
            {
                ConvertImagesToJpeg = true,
                ImageQuality = PdfJpegImageQuality.Low
            };
            using (FileStream pdfStream = new FileStream("Result.pdf", FileMode.Create))
            {
                await workbook.ExportToPdfAsync(pdfStream, pdfOptions,
                    cancellationToken,
                    new Progress<int>((progress) => Console.WriteLine($"{progress}%")));
            }
            Console.WriteLine("Done!");
        }
    }
    catch (OperationCanceledException) {
        Console.WriteLine("Cancelled by timeout.");
    }
    finally {
        cancellationSource.Dispose();
    }
}
vb
Imports System
Imports System.IO
Imports System.Threading
Imports System.Threading.Tasks
Imports DevExpress.Spreadsheet
Imports DevExpress.XtraPrinting

Module Example
    Sub Main()
        MainAsync().Wait()
    End Sub
    Async Function MainAsync() As Task
        Dim cancellationSource As New CancellationTokenSource(TimeSpan.FromSeconds(30))
        Dim cancellationToken As CancellationToken = cancellationSource.Token
        Try
            Using workbook As New Workbook()
                Console.WriteLine("Loading a document...")
                Using docStream As New FileStream("Document.xlsx", FileMode.Open)
                    Await workbook.LoadDocumentAsync(docStream, DocumentFormat.Xlsx, 
                        cancellationToken, 
                        New Progress(Of Integer)(Sub(progress) Console.WriteLine($"{progress}%")))
                End Using
                Console.WriteLine("Exporting to PDF...")
                ' Specify PDF export options.
                Dim pdfOptions As New PdfExportOptions() With {
                    .ConvertImagesToJpeg = True,
                    .ImageQuality = PdfJpegImageQuality.Low
                }
                Using pdfStream As New FileStream("Result.pdf", FileMode.Create)
                    Await workbook.ExportToPdfAsync(pdfStream, pdfOptions,
                        cancellationToken, 
                        New Progress(Of Integer)(Sub(progress) Console.WriteLine($"{progress}%")))
                End Using
                Console.WriteLine("Done!")
            End Using
        Catch e1 As OperationCanceledException
            Console.WriteLine("Cancelled by timeout.")
        Finally
            cancellationSource.Dispose()
        End Try
    End Function
End Module

Calculate Formulas in the Loaded Document

The default calculation mode for a Workbook is Manual. This mode implies that the Spreadsheet does not recalculate formulas when you load a document. Call the Workbook.Calculate or Workbook.CalculateFull method to recalculate all formulas in the workbook.

csharp
using (Workbook workbook = new Workbook())
{
    // Load a document.
    // ...
    // Calculate formulas in the document.
    workbook.Calculate();
    // ...
}
vb
Using workbook As New Workbook()
    ' Load a document.
  ' ...
    ' Calculate formulas in the document.
    workbook.Calculate()
    ' ...
End Using

Change Calculation Mode

Use the Workbook.Options.CalculationMode property to change the calculation mode for a Workbook.

The following calculation modes are available:

  • Manual (default) - Formulas are calculated only on demand (after the Calculate method call). It allows you to improve document generation speed for large workbooks with multiple formulas.

  • UseDocumentSettings - Uses the calculation mode specified in the loaded document (this value is stored in the Workbook.DocumentSettings.Calculation.Mode property).

  • Automatic - Recalculates formulas each time a cell value, formula, or defined name changes.

  • C#

  • VB.NET

csharp
using (Workbook workbook = new Workbook())
{
    // Change the calculation mode.
    workbook.Options.CalculationMode = WorkbookCalculationMode.UseDocumentSettings;
    // ...
    // Load a document.
    // ...
}
vb
Using workbook As New Workbook()
  ' Change the calculation mode.
  workbook.Options.CalculationMode = WorkbookCalculationMode.UseDocumentSettings
  ' ...
  ' Load a document.
  ' ...
End Using

See Also

Workbook Class

Workbook Members

DevExpress.Spreadsheet Namespace