Delete top 3 lines from xls using excel.interop.object library

I am using excel.interop.object library 9.0 to manage my xls file in C #

Assuming I have xls, which has 5 sheets. All sheets have multiple lines.

I use the following code to remove the top two lines from each sheet in my xls

Excel.Application excelApp = new Excel.Application(); Excel.Workbook excelWorkbook = excelApp.Workbooks.Open(mstrFilePath, 1, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, false, null, false); try { Excel.Sheets excelWorkSheet = excelWorkbook.Sheets; foreach (Excel.Worksheet work in excelWorkSheet) { Excel.Range range = work.get_Range("A1", "A3"); Excel.Range entireRow = range.EntireRow; // update for (int i = 1; i <= 3; i++) { entireRow.Delete(Excel.XlDirection.xlUp); } } //excelWorkbook.Close(false, mstrFilePath, null); } catch (Exception ex) { } finally { excelApp.Quit(); } 

But this incorrectly leads to the removal of 2 rows from sheet 3 and does not delete any rows from any other sheet.

what's wrong here?

+4
source share
1 answer

Delete for the loop (for (int i = 1; i <= 3; i ++)) in your code it will work.

You have already selected a range from A1 to A3 (three lines) .........

 Excel.Range range = work.get_Range("A1", "A3"); 

So no loop again for the same range as below .....

 //for (int i = 1; i <= 3; i++) //{ entireRow.Delete(Microsoft.Office.Interop.Excel.XlDirection.xlUp); //} 
+6
source

All Articles