简体   繁体   English

如何从Excel中删除除C#中的标头之外的所有行

[英]How to delete all rows from excel except header in c#

How do I delete all rows in an excel spreadsheet except the header in c#? 如何删除Excel电子表格中除C#中的标头之外的所有行?

I am trying to do this using the Microsoft.Office.Interop.Excel; 我正在尝试使用Microsoft.Office.Interop.Excel; library 图书馆

I now have this code 我现在有这个代码

        Range xlRange = ws.UsedRange;
        int rows = xlRange.Rows.Count;

        Console.WriteLine(rows);

        for (int i = 2; i <= rows; i++)
        {
            ((Range)ws.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
        }

But it's not deleting all the rows, I think because it's deleting the rows when it hits a certain number that row is no longer there, what have I done wrong? 但这并不是删除所有行,我想是因为它是在达到某个数字时删除行,该行不再存在,我做错了什么?

I managed to do it, I have started from the bottom instead of the top, so now my loop is 我设法做到了,我从底部开始,而不是从顶部开始,所以现在我的循环是

        for (int i = rows; i != 1; i--)
        {
            ((Range)ws.Rows[i]).Delete(XlDeleteShiftDirection.xlShiftUp);
        }

Solution

var range = (Range)ws.Range[ws.Cells[2, 1], ws.Cells[ws.UsedRange.Rows.Count, ws.UsedRange.Columns.Count]];
range.Delete(XlDeleteShiftDirection.xlShiftUp);

There had been a change in v4 of .Net that using get_Range stopped working .net的v4版本发生了变化,使用get_Range停止了工作

If you were working in Excel, you would keep hitting delete on the second row, and observe the rows below shifting up, replacing the cells that were previously occupied by the deleted row. 如果您使用的是Excel,则将继续在第二行上单击Delete,并观察下面的行向上移动,用删除的行替换以前占用的单元格。

To replicate that behavior in automation: 要在自动化中复制该行为:

for (int i = 2; i <= rows; i++)
{
    ((Range)ws.Rows[2]).Delete(XlDeleteShiftDirection.xlShiftUp);
}

Note that you can also construct a range up front, and delete that without a loop, which will be much faster: 请注意,您还可以预先构造一个范围,并在不循环的情况下将其删除,这样会更快:

var range = (Range)ws.get_Range(
    ws.Cells[1,2],
    ws.Cells[ws.UsedRange.Cols.Count,ws.UsedRange.Rows.Count]
);
range.Delete(XlDeleteShiftDirection.xlShiftUp);

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

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