Reputation: 2735
I'm simply trying to edit a spreadsheet that has text already written into to change the text to be blank.
However it's not working. The method seems to do nothing.
My code is:
public static void ClearCells(string SpreadsheetFilePath)
{
var SpreadsheetPath = new FileInfo(SpreadsheetFilePath);
var package = new ExcelPackage(SpreadsheetPath);
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
currentWorksheet.SetValue(1, 1, "hello123");
}
}
}
There is no runtime error. It runs, completes and the spreadsheet is unchanged. I don't know why.
Upvotes: 4
Views: 1714
Reputation: 1139
Try something like this:
public static void ClearCells(string SpreadsheetFilePath)
{
var excelFile = new FileInfo(SpreadsheetFilePath);
var excelPack = ExcelPackage(excelFile);
var workSheet = excelPack.Workbook.Worksheets.Add("Content"); // New worksheet
workSheet.Cells[1, 1].Value = "hello123";
excelPack.Save();
}
Upvotes: 1
Reputation: 19199
Just call package.Save();
after you are done editing your file.
var SpreadsheetPath = new FileInfo(@"C:\temp\abc.xlsx");
var package = new ExcelPackage(SpreadsheetPath);
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
currentWorksheet.SetValue(1, 1, "hello123");
}
}
package.Save(); // <========= MISSING IN YOUR CODE
Upvotes: 6
Reputation: 397
How about using SetCellValue
instead of SetValue
?
public static void ClearCells(string SpreadsheetFilePath)
{
var SpreadsheetPath = new FileInfo(SpreadsheetFilePath);
var package = new ExcelPackage(SpreadsheetPath);
ExcelWorkbook workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
ExcelWorksheet currentWorksheet = workBook.Worksheets.First();
currentWorksheet.SetCellValue(1, 1, "hello123");
}
}
}
Upvotes: -1