使用c#从excel文件中删除行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9951188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 11:21:24  来源:igfitidea点击:

deleting rows from an excel file using c#

c#.netexcel

提问by l--''''''---------''''''''''''

I am opening an excel file like this:

我正在打开一个这样的excel文件:

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 SomeStringdoes not appear in column A?

我想知道:
如何遍历所有行并删除SomeString没有出现字符串的每一行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

但我不知道如何删除整行

回答by Mircea Ion

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

其中 shiftDirection 见此处:Range.Delete 方法

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

您可能必须将单元格的内容转换为字符串。

回答by M Hanif

 for (int i = dt.Rows.Count - 1; i >= 0; i--)
 {
     if (dt.Rows[i][1].ToString() == "SomeThing")
     {
         dt.Rows.RemoveAt(i);
     }
 }