2014-02-06 15 views
0

我想使用C#在Excel中获取非连续的多区域范围的值。我已经看到another SO question,说我可以做这样的事情:Excel:来自多个区域的范围的值

obj[,] data = sheet.get_Range("B4:K4,B5:K5").get_Value(); 

然而,当我检查的结果我看到,我只能从第一区中的数据:"B4:K4"

进一步的测试,我发现,如果我要求以下列方式中的数据:

obj[,] data = sheet.get_Range("B4:K4","B5:K5").get_Value(); 

我得到的数据,这两个领域...

所以,我的问题是,有没有以编程方式组合区域地址(例如"B4:K4,B5:K5")以便获取它们引用的所有数据的方法?

感谢

+0

难道这是它会工作时,你使用分号而不是逗号?有时候,excel对这些事情很有趣......这只是一个预感/猜测! – Floris

+0

@pnuts:我忘了说区域可以不连续。上面编辑。 –

+0

http://msdn.microsoft.com/en-us/library/office/aa213609%28v=office.11​​%29.aspx也许? – pnuts

回答

1

我想出了解决的办法是不优雅,我希望的,但它仍然技巧:

public List<List<object>> 
GetNonContiguousRowValue(Excel.Worksheet ws, string noncontiguous_address) 
{ 
    var addresses = noncontiguous_address.Split(','); // e.g. "A1:D1,A4:D4" 
    var row_data = new List<List<object>>(); 

    // Get the value of one row at a time: 
    foreach (var addr in addresses) 
    { 
     object[,] arr = ws.get_Range(addr).Value; 
     List<object> row = arr.Cast<object>) 
           .Take(arr.GetLength(dimension:1)) 
           .ToList<object>(); 
     row_data.Add(row); 
    } 
    return row_data; 
} 

希望这可以帮助其他人...

0

如果您试图从隐藏行的范围表中获取数据,另一种方法是获取可见单元格,并将它们复制到新的工作表中。当粘贴时,它们将形成一个连续的区域,并且可以检索正常的对象[,]数组。

public object[,] GetNonContiguousVisibleRowsData(Excel.Worksheet sheet, string noncontiguous_address) 
{ 
    // Add a new worksheet 
    Excel.Workbook book = (Excel.Workbook)sheet.Parent; 
    Excel.Sheets sheets = book.Sheets; 
    Excel.Worksheet tempSheet = (Excel.Worksheet)sheets.Add(); 
    Excel.Range cellA1 = tempSheet.get_Range("A1"); 

    // Get only the visible cells 
    Excel.Range nonContiguousRange = sheet.get_Range(noncontiguous_address); 
    Excel.Range visibleSourceRange = nonContiguousRange.SpecialCells(Excel.XlCellType.xlCellTypeVisible); 

    // Copying the visible cells will result in a contiguous range in tempSheet 
    visibleSourceRange.Copy(cellA1); 

    // Get the contiguous range and copy the cell value. 
    Excel.Range contiguousRange = tempSheet.UsedRange; 
    object[,] data = (object[,])contiguousRange.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault); 

    // Release all COM objects from temp sheet, e.g.: 
    // System.Runtime.InteropServices.Marshal.ReleaseComObject(contiguousRange); 
    // contiguousRange = null; 

    tempSheet.Delete(); 

    // release all other COM objects 

    return data; 
} 
0

另一种方法是将非连续区域组合到一个命名区域中,并在C#代码中引用该命名区域。这里是一个办法做到这一点(这个公式分配到Excel名称管理器中的命名范围):

=CHOOSE({1;2;3},Sheet1!$A$1,Sheet2!$A$3,Sheet3!$A$5) 

的缺点用这种方法是,每个区只能是1排高。