I am developing an MVC project using .NET Framework 4.8.
I use DocumentEditorContainer for Word documents and Spreadsheet for Excel documents. I list Word and Excel files in a table. When a Word file is selected, it opens in a new page, and the user can edit it and save changes to the server using a save button (btnSave). I handle the logic with JavaScript on the Razor page and an API on the server side.
This flow works fine for Word documents, but I couldn't implement the same functionality for Excel files using the Spreadsheet component.
How can I open, edit, and save Excel documents to the server in a similar way?
Thanks in advance.
Hi Oguz Unlu,
Thank you for reaching out.
We understand that you're looking to implement similar functionality for Excel files using the Spreadsheet component, just as you’ve done with Word documents in your .NET Framework MVC project. We're happy to confirm that the Spreadsheet component does support loading and saving Excel files through the server.
To achieve this, you can use a server-side API to manage the file operations, similar to how you’re currently handling Word documents. When loading an Excel file, the server should retrieve the file from the desired location, convert it to Spreadsheet-compatible JSON, and return it to the client. On the client-side, this JSON data can then be loaded into the Spreadsheet using the openFromJson method.
Likewise, to save an Excel file, the Spreadsheet data should first be converted to JSON using the saveAsJson method on the client. This JSON is then sent to the server, where it is converted back into an Excel file and saved to the specified location.
To help illustrate this, we’ve prepared a working MVC sample in which three Excel files are placed in the local server Files folder, and three corresponding buttons are provided on the client side. Clicking any of these buttons will fetch the respective Excel file from the local server's Files folder, convert it to JSON, and load it into the Spreadsheet using the openFromJson method. When the Save button is clicked, the current spreadsheet data is converted to JSON using the saveAsJson method, sent to the server, and then saved as an Excel file back into the local server Files folder.
For your convenience, we’ve shared the sample along with the relevant code snippets for your reference.
Code Snippet:
|
[Index.cshtml]: <div class="container"> @Html.EJS().Spreadsheet("spreadsheet").OpenUrl("Home/Open").SaveUrl("Home/Save").Created("created").Render() </div>
<script>
var loadedFileName;
// To open an excel file from server location. function loadExcel() { const spreadsheet = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); // Fetch call to server to load the Excel file. fetch('Home/LoadExcel', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ FileName: loadedFileName }), }).then((response) => response.json()).then((data) => { // Load the JSON data into spreadsheet. spreadsheet.openFromJson({ file: data }); }); }
// To save an excel to a server location function saveExcel() { const spreadsheet = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); spreadsheet.saveAsJson().then((json) => { const formData = new FormData(); formData.append('FileName', loadedFileName); formData.append('saveType', 'Xlsx'); // Passing the JSON data to perform the save operation. formData.append('JSONData', JSON.stringify(json.jsonObject.Workbook)); formData.append('PdfLayoutSettings', JSON.stringify({ FitSheetOnOnePage: false })); // Using fetch to invoke the save process. fetch('Home/SaveExcel', { method: 'POST', body: formData }).then((response) => { console.log(response); }); }); }
function created() { const spreadsheet = ej.base.getComponent(document.getElementById('spreadsheet'), 'spreadsheet'); document.getElementById('load-btns').onclick = function (e) { const fileName = e.target.textContent; if (fileName) { loadedFileName = fileName; loadExcel(); } }; document.getElementById('save').onclick = function (e) { if (loadedFileName) { saveExcel(); } }; }
</script>
[Controller.cs]: public string LoadExcel(FileOptions file) { FileStream fs = System.IO.File.Open(HttpContext.Server.MapPath("~/Files/") + file.FileName + ".xlsx", FileMode.Open); // converting excel file to stream MemoryStream memoryStream = new MemoryStream(); fs.CopyTo(memoryStream); memoryStream.Position = 0; HttpPostedFileBase fileBase = (HttpPostedFileBase)new HttpPostedFile(memoryStream.ToArray(), file.FileName + ".xlsx"); HttpPostedFileBase[] files = new HttpPostedFileBase[1]; files[0] = fileBase; OpenRequest open = new OpenRequest(); open.File = files; fs.Close(); // Returns spreadsheet compatible Workbook JSON return Workbook.Open(open); }
public class FileOptions { public string FileName { get; set; } }
public string SaveExcel(SaveSettings saveSettings) { ExcelEngine excelEngine = new ExcelEngine(); IApplication application = excelEngine.Excel; try {
// Save the workbook as stream. Stream fileStream = Workbook.Save<Stream>(saveSettings); // Using XLSIO, we are opening the file stream and saving the file in the server under "Files" folder. // You can also save the stream file in your server location. IWorkbook workbook = application.Workbooks.Open(fileStream); string basePath = HttpContext.Server.MapPath("~/Files/") + saveSettings.FileName + ".xlsx"; var file = System.IO.File.Create(basePath); fileStream.Seek(0, SeekOrigin.Begin); // To convert the stream to file options. fileStream.CopyTo(file); file.Dispose(); fileStream.Dispose(); return string.Empty; } catch (Exception ex) { return ex.Message; } } }
|
Sample Link: https://drive.google.com/file/d/1qMx6t7H-0kJBGyZf3o5_AeZL2JjllfAx/view?usp=sharing
Steps to Run the Sample:
For more detailed information, you may also
refer to the documentation available in the following links:
User Guide (UG):
Open Save in ASP.NET MVC Syncfusion Spreadsheet Component(Save an Excel to server location)
Open Save in ASP.NET MVC Syncfusion Spreadsheet Component(Open an Excel file from server location)
Knowledge Base (KB): How to set the printing to
fit the page in Spreadsheet?
Please take a moment to review the shared details, and let us know if you have any further questions or need additional assistance.
Best regards,
Dinakar M
Hello,
The code worked.
Thank you
Hello Oguz Unlu ,
You're welcome! We're glad to hear the provided solution worked as expected. If you have any further questions or need assistance with anything else, feel free to reach out.
Best Regards,
Dinakar M