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

本文关键字:单元格 范围 数字 获取 包含 数据 | 更新日期: 2023-09-27 18:24:45

有一个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);

但它引发了一个"找不到细胞"的猜测

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

我真的不知道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

VSTO中的SpecialCells

如何在excel表格中获取已占用单元格的范围