reference the Microsoft Excel 10.0 Object Library in your project.
set the following using statement:
using
Excel = Microsoft.Office.Interop.Excel;
In your class, declare the following variables:
private
Excel.Application _app;
private Excel.Workbooks _books;
private Excel.Workbook _book;
protected Excel.Sheets _sheets;
protected Excel.Worksheet _sheet;
then open the workbook in the following method:
protected
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;
}
}
Make sure you have a method that will close the workbook
protected void CloseExcelWorkbook() {
_book.Save();
_book.Close(false, Type.Missing, Type.Missing);
}
and you need a method to clean up references to Excel objects (since they are COM), otherwise Excel will remain running.
protected void NAR(object o) {
try {
if(o != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
}
finally {
o = null;
}
}
Now you can select the worksheet you want to remove a row on:
OpenExcelWorkbook(@"d:\temp\yourworkbook.xls");
_sheet = (Excel.Worksheet)_sheets[1];
_sheet.Select(Type.Missing);
Excel.Range range = _sheet.get_Range("A7:A7", Type.Missing);
range.Delete(Excel.XlDeleteShiftDirection.xlShiftUp);
NAR(range);
NAR(_sheet);
CloseExcelWorkbook();
NAR(_book);
_app.Quit();
NAR(_app);