繁体   English   中英

如何在Excel工作表中获取占用单元格的范围

[英]How to get the range of occupied cells in excel sheet

我使用C#来自动化Excel文件。 我能够得到工作簿及其包含的工作表。 例如,如果我在sheet1中有两个列和5行。 我想要o将占用的单元格范围设为A1:B5。 我尝试了以下代码,但未给出正确的结果。 #列和#列要大得多,单元格也为空。

     Excel.Range xlRange = excelWorksheet.UsedRange;
     int col = xlRange.Columns.Count;
     int row = xlRange.Rows.Count;

我还有其他方法可以使用该范围吗?

我遇到了一个与您非常相似的问题。 实际起作用的是:

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

//These two lines do the magic.
xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

iTotalColumns = xlWorkSheet.UsedRange.Columns.Count;
iTotalRows = xlWorkSheet.UsedRange.Rows.Count;

恕我直言,发生的事情是,当您从Excel中删除数据时,它一直认为这些单元格中有数据,尽管它们是空白的。 当我清除格式后,它将删除空白单元格,因此返回实际计数。

Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);

现在,“范围”将是占用的单元格范围

请参见Range.SpecialCells方法。 例如,要获取具有恒定值或公式的单元格,请使用:

_xlWorksheet.UsedRange.SpecialCells(
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeConstants |
        Microsoft.Office.Interop.Excel.XlCellType.xlCellTypeFormulas)

我可以使它在所有情况下(受保护的工作表除外)工作的唯一方法(基于Farham的回答):

它支持:

  • 扫描隐藏的行/列

  • 忽略没有数据/公式的格式化单元格

码:

// Unhide All Cells and clear formats
sheet.Columns.ClearFormats();
sheet.Rows.ClearFormats();

// Detect Last used Row - Ignore cells that contains formulas that result in blank values
int lastRowIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                InteropExcel.XlFindLookIn.xlValues,
                InteropExcel.XlLookAt.xlWhole,
                InteropExcel.XlSearchOrder.xlByRows,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Row;
// Detect Last Used Column  - Ignore cells that contains formulas that result in blank values
int lastColIgnoreFormulas = sheet.Cells.Find(
                "*",
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value,
                InteropExcel.XlSearchOrder.xlByColumns,
                InteropExcel.XlSearchDirection.xlPrevious,
                false,
                System.Reflection.Missing.Value,
                System.Reflection.Missing.Value).Column;

// Detect Last used Row / Column - Including cells that contains formulas that result in blank values
int lastColIncludeFormulas = sheet.UsedRange.Columns.Count;
int lastColIncludeFormulas = sheet.UsedRange.Rows.Count;
dim lastRow as long   'in VBA it's a long 
lastrow = wks.range("A65000").end(xlup).row

这两行本身对我不起作用:

xlWorkSheet.Columns.ClearFormats();
xlWorkSheet.Rows.ClearFormats();

您可以通过单击工作表中的ctrl + end并查看选择了哪个单元格来进行测试。

我发现在前两个之后添加此行可以解决我遇到的所有实例的问题:

Excel.Range xlActiveRange = WorkSheet.UsedRange;

现在有点老问题了,但是如果有人正在寻找解决方案,那么这对我有用。

using Excel = Microsoft.Office.Interop.Excel;

Excel.ApplicationClass excel = new Excel.ApplicationClass();
Excel.Application app = excel.Application;
Excel.Range all = app.get_Range("A1:H10", Type.Missing);

如果您知道从何处查找范围,则应尝试使用currentRegion属性。 这将为您提供使用范围的边界。

这是专门为查找公式而设计的,但是您应该能够通过更改测试起始单元格的方式将其扩展为常规内容。 您必须处理超出此范围的单个单元格范围。

    public static Range GetUsedPartOfRange(this Range range)
    {
        Excel.Range beginCell = range.Cells[1, 1];
        Excel.Range endCell = range.Cells[range.Rows.Count, range.Columns.Count];

        if (!beginCell.HasFormula)
        {
            var beginCellRow = range.Find(
                "*",
                beginCell,
                XlFindLookIn.xlFormulas,
                XlLookAt.xlPart,
                XlSearchOrder.xlByRows,
                XlSearchDirection.xlNext,
                false);

            var beginCellCol = range.Find(
                "*",
                beginCell,
                XlFindLookIn.xlFormulas,
                XlLookAt.xlPart,
                XlSearchOrder.xlByColumns,
                XlSearchDirection.xlNext,
                false);

            if (null == beginCellRow || null == beginCellCol)
                return null;

            beginCell = range.Worksheet.Cells[beginCellRow.Row, beginCellCol.Column];
        }

        if (!endCell.HasFormula)
        {
            var endCellRow = range.Find(
            "*",
            endCell,
            XlFindLookIn.xlFormulas,
            XlLookAt.xlPart,
            XlSearchOrder.xlByRows,         
            XlSearchDirection.xlPrevious,
            false);

            var endCellCol = range.Find(
                "*",
                endCell,
                XlFindLookIn.xlFormulas,
                XlLookAt.xlPart,
                XlSearchOrder.xlByColumns,
                XlSearchDirection.xlPrevious,
                false);

            if (null == endCellRow || null == endCellCol)
                return null;

            endCell = range.Worksheet.Cells[endCellRow.Row, endCellCol.Column];
        }

        if (null == endCell || null == beginCell)
            return null;

        Excel.Range finalRng = range.Worksheet.Range[beginCell, endCell];

        return finalRng;
    }
}

您不应该通过按“删除”来删除框中的数据,我认为这就是问题所在,因为excel仍会检测到该框为“” <-仍然有值,您应该通过右键单击该框并单击“删除”来删除。

暂无
暂无

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

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