Masoud A

Masoud A

  • NA
  • 30
  • 19k

[C#] Processing on Data (Excel)

Sep 3 2015 10:24 PM
Greetings
 
 I am trying to delete a row from excel file, however it keeps giving me " System.NullReferenceException was unhandled", Can you please look at my code? thank you.
 
 
 
private void btRun_Click(object sender, EventArgs e)
{
public Excel.Application _app;
public Excel.Workbooks _books;
public Excel.Workbook _book;
public Excel.Sheets _sheets;
public Excel.Worksheet _sheet;

Rows a = new Rows();

a.OpenExcelWorkbook(label2.Text);

_sheet = (Excel.Worksheet)_sheets[1];   // i get the "System.NullReferenceException was unhandled" here
_sheet.Select(Type.Missing);
Excel.Range range = _sheet.get_Range("A1:A1", Type.Missing);
range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);

a.NAR(range);
a.NAR(_sheet);
a.CloseExcelWorkbook();
a.NAR(_book);
_app.Quit();
a.NAR(_app);
}
 
And 
 
class Rows
{

public Excel.Application _app;
public Excel.Workbooks _books;
public Excel.Workbook _book;
public Excel.Sheets _sheets;
public Excel.Worksheet _sheet;

public void OpenExcelWorkbook(string fileName)
{
_app = new Excel.Application();

if (_book == null)
{
_books = _app.Workbooks;
_book = _books.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
_sheets = _book.Worksheets;
}
}

public void CloseExcelWorkbook()
{
_book.Save();
_book.Close(false, Type.Missing, Type.Missing);
}

public void NAR(object o)
{
try
{
if (o != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}

finally
{
o = null;
}

}

Answers (3)