从 Excel 读取(范围到多维数组)C#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/910400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 02:36:50  来源:igfitidea点击:

Reading from Excel (Range into multidimensional Array) C#

c#excelmultidimensional-array

提问by Houman

How would I read from an Excel sheet and load the marked selection (Area) into an multidimensional array? A column in Excel could itself be a multi dimensional array since it would contain more than just one value.

我如何从 Excel 工作表中读取并将标记的选择(区域)加载到多维数组中?Excel 中的一列本身可以是一个多维数组,因为它包含多个值。

The idea (not sure how good or bad this is) is right now is to do a for loop through all the Excel.Area (selected fields) and add the content of that field to the multi dimensional array. Since the multi dimensional array is of type object[,] and therefore non-generic there is no convenient add() method to it. All of it needs to be done manually.

现在的想法(不确定这有多好或多坏)是对所有 Excel.Area(选定字段)执行 for 循环,并将该字段的内容添加到多维数组中。由于多维数组是 object[,] 类型,因此是非泛型的,因此没有方便的 add() 方法。所有这些都需要手动完成。

Any idea if this approach is OK or if it could be done more efficiently?

知道这种方法是否可行,或者是否可以更有效地完成?

采纳答案by TcKs

You can read the value of Range as array:

您可以将 Range 的值读取为数组:

using (MSExcel.Application app = MSExcel.Application.CreateApplication()) 
{
    MSExcel.Workbook book1 = app.Workbooks.Open( this.txtOpen_FilePath.Text);
    MSExcel.Worksheet sheet = (MSExcel.Worksheet)book1.Worksheets[1];
    MSExcel.Range range = sheet.GetRange("A1", "F13");

    object value = range.Value; //the value is boxed two-dimensional array
}

This code snippet is from .NET wrapper for MS Office. But same princip is in VSTO or VBA in MS Excel.

此代码片段来自MS Office 的 .NET 包装器。但同样的原理在 MS Excel 中的 VSTO 或 VBA 中。

回答by Joe Erickson

Here is the C# code to do this with SpreadsheetGear:

这是使用SpreadsheetGear执行此操作的 C# 代码:

    // Load the workbook.
    SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook(@"MyWorkbook.xlsx");
    // Get a range of cells as an array of object[,].
    object[,] values = (object[,])workbook.Worksheets["MySheet"].Cells["A1:J10"].Value;

SpreadsheetGear also provides fast APIs for accessing cells one at a time so that you can avoid copying the values to an array without sacrificing performance.

SpreadsheetGear 还提供了一次访问一个单元格的快速 API,这样您就可以在不牺牲性能的情况下避免将值复制到数组中。

Disclaimer: I own SpreadsheetGear LLC

免责声明:我拥有 SpreadsheetGear LLC