Search and replace text in Excel file using OPEN XML SDK
static void SearchAndReplaceTextInExcel(string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fs, true))
{
WorkbookPart
workbookPart = doc.WorkbookPart;
SharedStringTablePart sstpart
= workbookPart.GetPartsOfType<SharedStringTablePart>().First();
SpreadSheet.SharedStringTable sst =
sstpart.SharedStringTable;
// Iterate through all the items in the SharedStringTable.
If the text already exists, return its index.
foreach (SpreadSheet.SharedStringItem item in sstpart.SharedStringTable.Elements<SpreadSheet.SharedStringItem>())
{
if (item.InnerText != ""
&& item.InnerText.ToString().Contains("Date"))
{
SpreadSheet.Text text2 =
item.Descendants<SpreadSheet.Text>().First();
text2.Text = DateTime.Now.ToString();
}
}
sstpart.SharedStringTable.Save();
}
}
}
No comments:
Post a Comment