C# and excel deleting rows

// Here is the answers to 
// 1. Delete entire row - Below rows will shift up
// 2. Delete few cells - Below cells will shift up
// 3. Clear few cells - No shifting

using Excel = Microsoft.Office.Interop.Excel;

Excel.Application ExcelApp = new Excel.Application();
                  Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(ResultFilePath);
                  ExcelApp.Visible = true;
                  Excel.Worksheet ExcelWorksheet = ExcelWorkbook.Sheets[1];

Excel.Range TempRange = ExcelWorksheet.get_Range("H11", "J15");

// 1. To Delete Entire Row - below rows will shift up
TempRange.EntireRow.Delete(Type.Missing);

// 2. To Delete Cells - Below cells will shift up
TempRange.Cells.Delete(Type.Missing);

// 3. To clear Cells - No shifting
TempRange.Cells.Clear();

You can use this. İt's working ...

    _Application docExcel = new Microsoft.Office.Interop.Excel.Application { Visible = false };
   dynamic workbooksExcel = docExcel.Workbooks.Open(@"C:\Users\mahmut.efe\Desktop\Book4.xlsx");
   var worksheetExcel = (_Worksheet)workbooksExcel.ActiveSheet;

   ((Range)worksheetExcel.Rows[2, Missing.Value]).Delete(XlDeleteShiftDirection.xlShiftUp);

   workbooksExcel.Save();
   workbooksExcel.Close(false);
   docExcel.Application.Quit();

For more information you can visit this web site


You can do it using a Range Object. I assume here that you are using Excel interop.

Let say you have your book open, then set the range then delete it It should look something like this

ApplicationClass excel = new ApplicationClass();
//Abrir libro y seleccionar la hoja adecuada aqui
//...

Microsoft.Office.Interop.Excel.Range cel = (Range)excel.Cells[rowIndex, columnIndex];
cel.Delete();

Tags:

C#

Excel