使用c#从excel文件中删除行 [英] deleting rows from an excel file using c#
本文介绍了使用c#从excel文件中删除行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在打开一个这样的excel文件:
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.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);
我想知道:
如何循环所有行和删除字符串 SomeString
中的每一行都不会出现在列A中
? / p>
我知道如何循环遍历每个值:
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);
}
}
但是我不知道如何删除整行
解决方案
一旦你有一个参考工作表说
<$ p $对于(int i = 1; i <= 100; i ++)
{
if(!worksheet.Cells [i,1] .Contains(SomeString),p>
)
{
((Range)worksheet.Rows [i])。删除(shiftDirection)
}
}
其中shiftDirection见这里: Range.Delete方法
您可能必须将单元格的内容转换为字符串。
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
解决方案
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.
这篇关于使用c#从excel文件中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文