How to: Implement Progress Notifications for Workbook Operations
- 3 minutes to read
The Spreadsheet Document API allows you to implement progress notifications for the following asynchronous methods:
Workbook.LoadDocumentAsync – loads a workbook from a file, stream, or byte array.
Workbook.SaveDocumentAsync – saves a workbook to a file, stream, or byte array.
Workbook.ExportToPdfAsync – exports a workbook to PDF.
Workbook.ExportToHtmlAsync – saves a workbook as HTML.
These methods accept an IProgress<T> parameter to report progress information for each operation. The <T> type is an integer that defines the progress percentage. Use the Progress<T> class as the default implementation of the IProgress<T> interface.
Example: Create a Progress Dialog
The example below demonstrates how to create a simple progress dialog that indicates the progress of load and PDF export operations.
A CancellationToken object is passed to the LoadDocumentAsync and ExportToPdfAsync methods to cancel operations when a user clicks Cancel or closes the form.
using System;
using System.Threading;
using System.Windows.Forms;
using DevExpress.Spreadsheet;
// ...
public partial class Form1 : DevExpress.XtraEditors.XtraForm
{
CancellationTokenSource cancellationSource;
public Form1() {
InitializeComponent();
}
private async void RunCancel_Click(object sender, EventArgs e) {
if (cancellationSource != null) {
cancellationSource.Cancel();
}
else {
progressBarLoad.Value = 0;
progressBarExport.Value = 0;
btnRunCancel.Text = "Cancel";
cancellationSource = new CancellationTokenSource();
try {
using (Workbook workbook = new Workbook()) {
await workbook.LoadDocumentAsync("Document.xlsx",
cancellationSource.Token,
new Progress<int>((progress) => {
progressBarLoad.Value = progress;
progressBarLoad.Refresh();
}));
await workbook.ExportToPdfAsync("Result.pdf",
cancellationSource.Token,
new Progress<int>((progress) => {
progressBarExport.Value = progress;
progressBarExport.Refresh();
}));
}
}
catch (OperationCanceledException) {
progressBarLoad.Value = 0;
progressBarExport.Value = 0;
}
finally {
cancellationSource.Dispose();
cancellationSource = null;
btnRunCancel.Text = "Run";
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
cancellationSource?.Cancel();
}
}