4

I am opening an excel file like this:

Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range range;

string str;
int rCnt = 0;
int cCnt = 0;

xlApp = new Excel.ApplicationClass();
xlWorkBook = xlApp.Workbooks.Open("csharp.net-informations.xls", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

I would like to know:
How do I loop through all the rows and delete every row in which the string SomeString does not appear in column A?

I know how to loop through every value:

for (rCnt = 1; rCnt <= range.Rows.Count; rCnt++)
{
    for (cCnt = 1; cCnt <= range.Columns.Count; cCnt++)
    {
        str = (string)(range.Cells[rCnt, cCnt] as Excel.Range).Value2;
        MessageBox.Show(str);
    }
}

But I do not know how to delete the entire row

4
  • 1
    You should be able to use: 'range.EntireRow.Delete(Excel.XLDirection.xlUp)' - just set the range with the worksheet object (xlWorksheet). Commented Mar 30, 2012 at 22:57
  • @PatrickPitre thanks so much! how do i set the range? Commented Apr 1, 2012 at 3:27
  • 1
    It would look like: range = xlWorksheet.get_Range("A1", "B1"); range.EntireRow.Delete(Excel.XLDirection.xlUp); Commented Apr 2, 2012 at 18:16
  • What library is being used? What usings? Commented Mar 25, 2015 at 15:31

2 Answers 2

15

Once you have a reference to the worksheet say

for(int i = 1; i <=100; i++)
{
  if(!worksheet.Cells[i,1].Contains("SomeString"))
  {
     ((Range)worksheet.Rows[i]).Delete(shiftDirection)
  }
}

where shiftDirection see here: Range.Delete method

You may have to cast the Cell's content to a string.

Sign up to request clarification or add additional context in comments.

Comments

-1

I know the question has been already answered, but you can try something like below

 for (int i = dt.Rows.Count - 1; i >= 0; i--)
     {
         if (!dt.Rows[i]["column A"].Contains("SomeString "))
         {
             dt.Rows.RemoveAt(i);
         }
     }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.