5

I want to use EPPLUS to clear a range of cells. I tried the syntax below, but it gives me an error of

object reference not set to an instance of an object

What would be the proper way to clear the contents of cells A24:C36 with EPPLUS?

ExcelPackage package = new ExcelPackage();

ExcelWorksheet ws = package.Workbook.Worksheets["Sheet1"];

ws.Cells["A24:C36"].Clear();
Ali Soltani
  • 9,589
  • 5
  • 30
  • 55

1 Answers1

6

Your code is correct. I think the .xlsx file does not have Worksheets with Sheet1 name.

For example, I created this excel file like this:

excel

I wanted to erase A24:C36. I encountered null reference error before executing ws.Cells["A24:C36"].Clear(); like this:

error

If I use code below instead of it, it works properly (Sheet2).

ExcelPackage package = new ExcelPackage();

ExcelWorksheet ws = package.Workbook.Worksheets["Sheet2"];

ws.Cells["A24:C36"].Clear();

Notice that having no value in A24:C36 does not make an error.

Ali Soltani
  • 9,589
  • 5
  • 30
  • 55
  • The OP code is not correct. `.Clear()` removes all contents, formatting, formulas, etc. If you want to clear contents, you will have to loop through each cell and assign the cell's Formula property to its Value – StingyJack Jul 22 '20 at 13:43