简体   繁体   English

C#Interop-遍历行并删除

[英]C# Interop - Iterating through rows and deleting

I am using Excel Interop to work with some excel sheets. 我正在使用Excel Interop处理一些Excel工作表。 In a worksheet, I need to iterate through the rows, and if the first cell in the row is empty then I need to delete the entire row iteself. 在工作表中,我需要遍历行,如果行中的第一个单元格为空,则需要删除整个行。 I tried the following- 我尝试了以下-

Excel.Range excelRange = sheet.UsedRange;
foreach (Excel.Range row in excelRange.Rows)
{
 String a = ((Excel.Range)row.Cells[Type.Missing, 1]).Value2 as String;
 if (a == null || a == "")
 {
  ((Excel.Range)row).Delete(Type.Missing);
 }
}

This was not working at all. 这根本没有用。 Is there any different way to do this? 有没有其他方法可以做到这一点?

And, is there any quick way to find and remove all formula in a Worksheet? 而且,是否有任何快速方法来查找和删除工作表中的所有公式?

Let's say your Excel file looks like this. 假设您的Excel文件如下所示。

在此处输入图片说明

The best way to delete rows would be to use Excel's inbuilt feature called Autofilter which will filter Col A for blank values and then deleting the entire rows in one go. 删除行的最佳方法是使用Excel的内置功能,称为自动过滤器,该功能将过滤Col A中的空白值,然后一次性删除整个行。

TRIED AND TESTED (In VS 2010 Ultimate) 经过测试(在VS 2010 Ultimate中)

Note : I have changed few lines which I feel could error out in VS 2008. Since I don't have VS 2008, I couldn't test it there. 注意 :我更改了几行,感觉在VS 2008中可能会出错。由于我没有VS 2008,因此无法在那里进行测试。 If you get any errors do let me know and I will rectify it. 如果您遇到任何错误,请告诉我,我将予以纠正。

//~~> Open File
private void button1_Click(object sender, EventArgs e)
{

    Microsoft.Office.Interop.Excel.Application xlexcel;
    Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
    Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
    Microsoft.Office.Interop.Excel.Range xlRange;
    Microsoft.Office.Interop.Excel.Range xlFilteredRange;

    xlexcel = new Excel.Application();

    xlexcel.Visible = true;

    //~~>  Open a File
    xlWorkBook = xlexcel.Workbooks.Open("C:\\MyFile.xlsx",  0,  false, 5, "", "", true,
    Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);

    //~~> Work with Sheet1
    xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

    //~~> Get last row in Col A
    int _lastRow = xlWorkSheet.Cells.Find(
                                  "*",
                                  xlWorkSheet.Cells[1,1],
                                  Excel.XlFindLookIn.xlFormulas,
                                  Excel.XlLookAt.xlPart,
                                  Excel.XlSearchOrder.xlByRows,
                                  Excel.XlSearchDirection.xlPrevious,
                                  misValue,
                                  misValue,
                                  misValue
                                  ).Row ;

    //~~> Set your range
    xlRange =  xlWorkSheet.Range["A1:A" + _lastRow];

    //~~> Remove any filters if there are
    xlWorkSheet.AutoFilterMode=false;

    //~~> Filter Col A for blank values
    xlRange.AutoFilter(1, "=", Excel.XlAutoFilterOperator.xlAnd, misValue, true);

    //~~> Identigy the range
    xlFilteredRange = xlRange.Offset[1,0].SpecialCells(Excel.XlCellType.xlCellTypeVisible,misValue);

    //~~> Delete the range in one go
    xlFilteredRange.EntireRow.Delete(Excel.XlDirection.xlUp);

    //~~> Remove filters
    xlWorkSheet.AutoFilterMode = false;

    //~~> Close and cleanup
    xlWorkBook.Close(true, misValue, misValue);
    xlexcel.Quit();

    releaseObject(xlRange);
    releaseObject(xlFilteredRange);    
    releaseObject(xlWorkSheet);
    releaseObject(xlWorkBook);
    releaseObject(xlexcel);
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Unable to release the Object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}

Output 产量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM