Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# and excel deleting rows

Tags:

c#

excel

I want to write from my form (in C#) to an excel spread sheet and delete certain rows if blank.

I can write perfectly fine to a speadsheet and save it, but lets say the user entered data into row a1, a2, a3, and a4, I now want to delete all the rows in between a4 and a29.

All I need is to find out how to delete a certain range of cells.

Thanks

like image 518
TheNoob Avatar asked Sep 03 '12 23:09

TheNoob


4 Answers

// 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();
like image 65
KR Akhil Avatar answered Oct 29 '22 17:10

KR Akhil


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();
like image 43
DkAngelito Avatar answered Oct 29 '22 19:10

DkAngelito


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

like image 11
Mahmut EFE Avatar answered Oct 29 '22 19:10

Mahmut EFE


You can specify a cell (eg. A1) and find the entire row containing that cell as a range and then can delete the row.

excel.Worksheet sheet = (excel.Worksheet)excelWorkBook.Sheets["sheet1"];    
excel.Range cells = (excel.Range)sheet.Range["A1", Type.Missing];    
excel.Range del = cells.EntireRow;    
del.Delete();

The above given code will delete first row from sheet1

like image 3
Akhila Avatar answered Oct 29 '22 17:10

Akhila