【问题标题】:Passing Excel Interop Values to Deedle DataFrame将 Excel 互操作值传递给 Deedle DataFrame
【发布时间】:2016-09-06 22:45:43
【问题描述】:

我有一个使用 Excel Interop 从 Excel 电子表格中提取的 2D Object Array

data = activeWorksheet.UsedRange.Value2;

data.GetType()
{Name = "Object[,]" FullName = "System.Object[,]"}

Looking at the Deedle documentation on Frames,看来我可以从 2D 数组 FromArray2D(array) 或“任何 .NET 对象的序列”FromRecords(values) 创建一个框架,但它似乎无法获取此对象数组。

我也尝试过强制转换为数组,但这只会给我一个 com 对象数组,我可以从中引用 Value2。所以这真的没有帮助。

cellArray = activeWorksheet.UsedRange.Cells.Cast<Excel.Range>().ToArray<Excel.Range>();

cellArray.GetType()
{Name = "Range[]" FullName = "Microsoft.Office.Interop.Excel.Range[]"}

我想我可以编写一个函数来重构我的数据,based on the Github examples,但在我这样做之前......

我应该考虑进行类型转换/强制转换以制作简单的 Excel -> Deedle DataFrame 插入吗?


编辑:

当尝试使用FromArray2D 时,我得到以下信息。

Frame df = Frame.FromArray2D(data);

'Frame.FromArray2D(data)' threw an exception of type 'System.IndexOutOfRangeException'
    Data: {System.Collections.ListDictionaryInternal}
    HResult: -2146233080
    HelpLink: null
    InnerException: null
    Message: "Index was outside the bounds of the array."
    Source: "Deedle"
    StackTrace: "   at Deedle.Frame.FromArray2D[T](T[,] array) in C:\\code\\deedle\\src\\Deedle\\FrameExtensions.fs:line 281\r\n   at System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)"
    TargetSite: {Deedle.Frame`2[System.Int32,System.Int32] FromArray2D[T](T[,])}

这可能是因为 Excel Interop 使用的是 1-index 数组,而不是 0-index,所以不匹配?

我在官方文档中找不到 Excel 的怪癖,但 SO 中到处都是答案。例如:https://stackoverflow.com/a/14345372/1886901

【问题讨论】:

  • 当您尝试使用FromArray2D 时遇到什么错误?
  • 更新了我的问题以包含FromArray2D的错误

标签: c# excel-interop deedle


【解决方案1】:

不确定这是否是最好的方法,但是将数组转换为 0 索引可以让 FromArray2D 顺利通过。

data = activeWorksheet.UsedRange.Value2;    
string[,] newData = new string[data.GetLength(0), data.GetLength(1)];
for (int x = 0; x < data.GetLength(0); x++)
{
  for (int y = 0; y < data.GetLength(1); y++)
  {
    newData[x, y] = data[x + 1, y + 1].ToString();
  }
}
var df = Frame.FromArray2D(newData);

【讨论】:

    猜你喜欢
    • 2019-02-12
    • 2016-10-07
    • 2013-08-07
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多