C#删除空白单元格

时间:2017-08-04 14:02:12

标签: c# excel-interop

    public static void ExportData()
    {
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkBook.Application.ScreenUpdating = false;
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        Excel.Range DR = (Excel.Range)xlWorkSheet.Columns["A:A"];
        DR.Select();
        DR.Delete();
        Excel.Range A1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        A1.Select();
    }

这是我现有的功能。最后,我想从Excel中复制这个VB代码;

    Columns("A:A").Select
    Selection.SpecialCells(xlCellTypeBlanks).Select
    Selection.EntireRow.Delete

我尝试了一些不同的选项来取代"选择"但我最接近的是,让C#侧选择空白单元格,但随后它会删除所有内容而不仅仅是所选文本。

任何人都有我可以进去的方向吗?

也使用;

using Excel = Microsoft.Office.Interop.Excel;

2 个答案:

答案 0 :(得分:0)

这应该是C#中的等价物:

Excel.Range selection = xlexcel.ActiveWindow.Selection;
Excel.Range blankCells = selection.SpecialCells( Excel.XlCellType.xlCellTypeBlanks );
blankCells.EntireRow.Delete();

答案 1 :(得分:0)

        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkBook.Application.ScreenUpdating = false;
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
        Excel.Range DR = (Excel.Range)xlWorkSheet.Columns["A:A"];
        DR.Select();
        DR.Delete();
        Excel.Range ACol = (Excel.Range)xlWorkSheet.Columns["A:A"];
        Excel.Range Ronge = ACol.SpecialCells(Excel.XlCellType.xlCellTypeBlanks);
        Ronge.EntireRow.Delete();
        Excel.Range A1 = (Excel.Range)xlWorkSheet.Cells[1, 1];
        A1.Select();
        xlWorkBook.Application.ScreenUpdating = true;

通过混合亨氏回答和其他一些变化进行管理,因为答案不会接受AddinGlobal。

如果将来有人需要,上述工作已经奏效。它将删除列" A"

中的所有空行