Save a Document
- 2 minutes to read
The Spreadsheet allows you to save an active document at any point in time. To initiate a save operation, send the Spreadsheet’s client state to the server within a POST request.
The example below illustrates how to send a POST request to the server once a user clicks an app’s custom Save button:
<div id="button-save"></div>
<script type="text/javascript">
$("#button-save").dxButton({
text: "Save",
onClick: function (e) {
var spreadsheetState = spreadsheet.getSpreadsheetState();
$.ajax({
type: 'POST',
url: '@Url.Action("SaveDocument")',
data: { spreadsheetState: spreadsheetState }
});
}
});
</script>
@(Html.DevExpress()
.Spreadsheet("spreadsheet")
)
On the server, use the GetSpreadsheetFromState method to access the server-side Spreadsheet object. Call this object’s Save() method to save the document that you opened from a file. If you opened a document from a byte array or stream, call the SaveCopy method overload to save the document to a file using custom storage:
public class SpreadsheetController : Controller {
public void SaveDocument(SpreadsheetClientState spreadsheetState) {
var spreadsheet = SpreadsheetRequestProcessor.GetSpreadsheetFromState(spreadsheetState);
// Saves an active document back to the file you opened it from
spreadsheet.Save();
// Saves a copy of an active document to a file in the server's file system.
spreadsheet.SaveCopy("your-file-path");
// Saves a copy of an active document to a byte array
byte[] documentContent = spreadsheet.SaveCopy(DocumentFormat.Xlsx);
// Saves a copy of an active document to a stream
var stream = new MemoryStream();
spreadsheet.SaveCopy(stream, DocumentFormat.Xlsx);
}
}
Enable Auto-Save Feature
The Spreadsheet can save an active document at regular intervals. Pass the On
mode to the AutoSaveMode method to enable auto-save feature. Call the AutoSaveTimeout method to set the control’s auto-save timeout period:
@(Html.DevExpress().Spreadsheet("spreadsheet")
// ...
.AutoSaveMode(DevExpress.Web.Office.AutoSaveMode.On)
.AutoSaveTimeout(TimeSpan.FromMinutes(3)))
The Spreadsheet cannot save the following documents:
- Documents with an empty identifier.
- Documents opened from a custom storage as a byte array or stream.
In such instances, you need to implement custom auto-save logic in the AddAutoSaving method (to save the document):
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
builder.Services.AddDevExpressControls(options => {
options.AddSpreadsheet(
spreadsheetOptions => {
spreadsheetOptions
.AddAutoSaving(
(IDocumentInfo documentInfo, DocumentSavingEventArgs e) => {
byte[] documentContent = documentInfo.SaveCopy();
// Your custom logic to save a document
e.Handled = true;
}
);
}
);
});