仅获取包含数据(数字)的单元格范围

时间:2012-02-16 13:40:37

标签: c# excel worksheet-function

有一个 MS Excel 表填充了一个矩阵数据。

如何才能获得数字区域?

现在我正在使用workSheet.UsedRange提取数据范围。但是如果我删除一个矩阵行,它将在usedRange中被考虑,即使该行已被删除!那只是因为我之前使用过这些细胞。

那么,我怎么能只获得实际内容(数字)的范围

代码:

public Array ReadData(string fullPath, Size size)
{
    Excel.Application application;
    Workbook workBook;
    Worksheet workSheet;
    Range range;

    application = new Excel.ApplicationClass();
    workBook = application.Workbooks.Open(fullPath, 0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
    workSheet = (Worksheet)workBook.Worksheets.get_Item(1);

    //HERE IS THE PROBLEM
    range = workSheet.UsedRange; 

    if (!size.IsEmpty)
    {
        Size availableSize = new Size(range.Columns.Count, range.Rows.Count);
        if ((availableSize.Width < size.Width) || (availableSize.Height < size.Height))
        {
            string msg = string.Format("Available data range ({0}) at the sheet is smaller than needed size ({1})", availableSize, size);
            throw new ArgumentException(msg);
        }
        else if ((availableSize.Width > size.Width) || (availableSize.Height > size.Height))
        {
            range = workSheet.get_Range(workSheet.Cells[1, 1], workSheet.Cells[size.Width, size.Height]);
            string msg = string.Format("Available data range ({0}) at the sheet is bigger than needed size ({1})", availableSize, size);
            Trace.TraceInformation(msg);
        }
    }

    Array data;

    data = (Array)range.Cells.Value2;

    return data;
}

我认为可能的解决方案是在VB中发布的。在C#中将是:

        range = workSheet.UsedRange;
        range = range.CurrentRegion.SpecialCells(XlCellType.xlCellTypeConstants, XlSpecialCellsValue.xlNumbers);

但它引发了一场“没有发现细胞”的问题

1 个答案:

答案 0 :(得分:1)

我真的不知道c#,但在Excel中,你使用
Range("yourRange").SpecialCells(xlCellTypeConstants, xlNumbers)或者 Range("yourRange").CurrentRegion.SpecialCells(xlCellTypeConstants, xlNumbers)

http://msdn.microsoft.com/en-us/library/aa213567(v=office.11).aspx

SpecialCells in VSTO

How to get the range of occupied cells in excel sheet