Skip to content

Instantly share code, notes, and snippets.

@GroupDocsGists
Last active February 7, 2022 03:45
Show Gist options
  • Save GroupDocsGists/a1079591c84b3338b58097d884bb2f0d to your computer and use it in GitHub Desktop.
Save GroupDocsGists/a1079591c84b3338b58097d884bb2f0d to your computer and use it in GitHub Desktop.
How to Edit Excel Files using C#
// Edit the Excel Spreadsheet using C#
Options.SpreadsheetLoadOptions loadOptions = new SpreadsheetLoadOptions();
// loadOptions.Password = "password";
// Load the Spreadsheet
Editor editor = new Editor("path/spreadsheet.xlsx", delegate { return loadOptions; });
// Get 1st tab of the Spreadsheet
SpreadsheetEditOptions sheetTab1EditOptions = new SpreadsheetEditOptions();
sheetTab1EditOptions.WorksheetIndex = 0; // first worksheet
// Obtain HTML markup from some EditableDocument instance
EditableDocument firstTab = editor.Edit(sheetTab1EditOptions);
string bodyContent = firstTab.GetBodyContent(); // HTML markup from inside the HTML -> BODY element
string allContent = firstTab.GetContent(); // Full HTML markup of all document, with HTML -> HEAD header and all its content
List<IImageResource> onlyImages = firstTab.Images;
List<IHtmlResource> allResourcesTogether = firstTab.AllResources;
string editedContent = allContent.Replace("Company Name", "New Company Name");
EditableDocument afterEdit = EditableDocument.FromMarkup(editedContent, allResourcesTogether);
// Load the Excel File using C#
Options.SpreadsheetLoadOptions loadOptions = new SpreadsheetLoadOptions();
loadOptions.Password = "password"; // if any
// Load the Spreadsheet
Editor editor = new Editor("path/spreadsheet.xlsx", delegate { return loadOptions; });
// Save the Excel file with the updated content using C#
// Create save options
SpreadsheetFormats xlsxFormat = SpreadsheetFormats.Xlsx;
Options.SpreadsheetSaveOptions saveOptions = new SpreadsheetSaveOptions(SpreadsheetFormats.Xlsx);
// Set new opening password
saveOptions.Password = "newPassword";
saveOptions.WorksheetProtection = new WorksheetProtection(WorksheetProtectionType.All, "WriteProtectionPassword");
// Create output stream
using (FileStream outputStream = File.Create("path/editedSpreadsheet.xlsx"))
{
editor.Save(afterEdit, outputStream, saveOptions);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment