Spreadsheet Document Encryption

Use the Spreadsheet Document API to encrypt and password-protect a workbook. Enter a password in the Password to Open box, select an encryption type and an output format. Click Download to save the document to your computer.

Options
Password to Open
Encryption Type
File Format
Download
@model AspNetCoreDemos.OfficeFileAPI.SpreadsheetDocumentEncryptionModel
@using DevExtreme.AspNet.Mvc

@{ Html.BeginForm("SpreadsheetDocumentEncryptionExportTo", "DocumentProtection", FormMethod.Post); }

<div class="demo-view-container">
    @await Html.PartialAsync("SpreadsheetPreviewPartial", Model.PreviewModel)
</div>

<div class="options">
    <div class="caption">Options</div>
    <div class="option">
        <div class="label">Password to Open</div>
        @(Html.DevExtreme().TextBoxFor(m => m.PasswordToOpen))
    </div>
    <div class="option">
        <div class="label">Encryption Type</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.EncryptionType)
                           .DataSource(Html.GetEnumSelectList<DevExpress.Spreadsheet.EncryptionType>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">File Format</div>
            @(Html.DevExtreme().SelectBoxFor(m => m.FileFormat)
                               .DataSource(Html.GetEnumSelectList<AspNetCoreDemos.OfficeFileAPI.SpreadsheetProtectionFileFormat>()
                               .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                               .ValueExpr("Value")
                               .DisplayExpr("Text")
            )
    </div>
    <div class="option-buttons">
            @(Html.DevExtreme().Button()
                               .Text("Download")
                               .Type(ButtonType.Default)
                               .StylingMode(ButtonStylingMode.Contained)
                               .UseSubmitBehavior(true)
            )
    </div>

</div>
@{ Html.EndForm(); }
@model AspNetCoreDemos.OfficeFileAPI.SpreadsheetPreviewModel

<iframe id="previewFrame" src="@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)" class="demo-preview-border" style="width: 100%; height: @Model.HeightInPixels;box-sizing:border-box"></iframe>

<script type="text/javascript">
    SpreadsheetPreview = {
        basePath: '@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)',
        Update: function (param) {
            var iframeElementName = "previewFrame";
            var iframeElement = document.getElementById(iframeElementName);
            if (!iframeElement)
                return;
            var additionalParams = "&" + new Date().valueOf();
            if (param)
                additionalParams = param;
            iframeElement.src = this.basePath + "?" + additionalParams;
        }
    };
</script>

using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class DocumentProtectionController : OfficeDemoController {
        public DocumentProtectionController(ILogger<DocumentProtectionController> logger, IWebHostEnvironment hostingEnvironment)
            : base(logger, hostingEnvironment) {
        }
        protected const string TsaServerUriInvalidExceptionString = "ERROR: TSA server URI is invalid or server doesn't support SHA-256 hashing algorithm";
    }
}
using System.IO;
using DevExpress.Spreadsheet;
using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class DocumentProtectionController {
        const string spreadsheetDocumentEncryptionDefaultFile = "/Documents/ProfitAndLoss.xlsx";

        public IActionResult SpreadsheetDocumentEncryption() {
            SpreadsheetDocumentEncryptionModel model = new SpreadsheetDocumentEncryptionModel();
            model.PreviewModel.Workbook = CreateEncryptedWorkbook(model);
            return View(model);
        }

        public IActionResult SpreadsheetDocumentEncryptionExportTo(SpreadsheetDocumentEncryptionModel model) {
            IWorkbook workbook = CreateEncryptedWorkbook(model);
            SpreadsheetFileFormat fileFormat = model.FileFormat;
            DocumentFormat format = SpreadsheetUtils.ConvertToFormat(fileFormat);
            MemoryStream stream = new MemoryStream();
            workbook.SaveDocument(stream, format);
            stream.Seek(0, SeekOrigin.Begin);
            string contentType = SpreadsheetUtils.ConvertToContentType(fileFormat);
            string fileExtension = SpreadsheetUtils.ConvertToFileExtension(fileFormat);
            return CreateFileStreamResult(stream, contentType, fileExtension);
        }

        public IActionResult SpreadsheetDocumentEncryptionPreview(SpreadsheetDocumentEncryptionModel model) {
            SpreadsheetPreviewModel previewModel = model.PreviewModel;
            previewModel.Workbook = CreateEncryptedWorkbook(model);
            return GenerateHtmlPreview(previewModel);
        }

        IWorkbook CreateEncryptedWorkbook(SpreadsheetDocumentEncryptionModel model) {
            IWorkbook workbook = new Workbook();
            string filePath = HostingEnvironment.ContentRootPath + spreadsheetDocumentEncryptionDefaultFile;
            workbook.LoadDocument(filePath);
            workbook.CalculateFull();
            workbook.DocumentSettings.Encryption.Password = model.PasswordToOpen;
            workbook.DocumentSettings.Encryption.Type = model.EncryptionType;
            return workbook;
        }
    }
}
using System.ComponentModel.DataAnnotations;
using DevExpress.Spreadsheet;

namespace AspNetCoreDemos.OfficeFileAPI {
    public class SpreadsheetDocumentEncryptionModel : SpreadsheetModelBase {
        public SpreadsheetDocumentEncryptionModel() {
            PreviewModel.PreviewDocumentAction = "SpreadsheetDocumentEncryptionPreview";
            PreviewModel.ControllerName = "DocumentProtection";
            PasswordToOpen = "test";
            EncryptionType = EncryptionType.Strong;
            FileFormat = SpreadsheetFileFormat.Xlsx;
        }

        public string PasswordToOpen { get; set; }
        public EncryptionType EncryptionType { get; set; }
    }
}
namespace AspNetCoreDemos.OfficeFileAPI {
    public class SpreadsheetModelBase {
        public SpreadsheetModelBase() {
            PreviewModel = new SpreadsheetPreviewModel();
            PreviewModel.OwnerPropertyName = "PreviewModel";
            FileFormat = SpreadsheetFileFormat.Xlsx;
        }

        public SpreadsheetFileFormat FileFormat { get; set; }
        public SpreadsheetPreviewModel PreviewModel { get; internal set; }
    }
}