f#read xls file - 如何解析value2对象

时间:2021-02-28 16:03:27

I tried to use F# read a xls file as below

我尝试使用F#读取xls文件,如下所示

open Microsoft.Office.Interop.Excel
let app = ApplicationClass(Visible = false)
let book = app.Workbooks.Open "test.xls"
let sheet = book.Worksheets.[1] :?> _Worksheet
let vals = sheet.UsedRange.Value2

The problem is how can I parse vals into a F# type? in fsx.exe, the vals showed as

问题是如何将val解析为F#类型?在fsx.exe中,val显示为

'val vals: obj = [bound1
                  bound2
                  ["colname1"; "colname2"; ...]
                  [1234,5678,]...]

I wanted to retrieve the string represetation first, but printfn "%A" vals.ToString();; shows "System.Object[,]" only. If I then try to access vals.[1,1], I got error The field,constructor or member 'item' is not defined

我想首先检索字符串表示,但printfn“%A”vals.ToString();;仅显示“System.Object [,]”。如果我然后尝试访问val。[1,1],我收到错误字段,构造函数或成员'item'未定义

thanks,

谢谢,

1 个解决方案

#1


3  

The type of Value2 is obj. If the range represents just a single cell, the actual type will be some primitive type (int, float, decimal, string). If the range represents several cells (your case), then the returned value is a two-dimensional .NET array of type obj[,].

对象2的类型是obj。如果范围仅表示单个单元格,则实际类型将是某种基本类型(int,float,decimal,string)。如果范围代表几个单元格(您的情况),则返回的值是obj [,]类型的二维.NET数组。

You can cast the value returned by Value2 to an array and access it using indexers:

您可以将Value2返回的值强制转换为数组并使用索引器访问它:

let vals = sheet.UsedRange.Value2 :?> obj[,]
vals.[1, 1]

Note that the returned array is 1-based (and not zero based as usual). The indexer again returns obj, so you need to cast the values to their actual type. Depending on your sheet, this will be probably float or string:

请注意,返回的数组是基于1的(并且不像通常那样基于零)。索引器再次返回obj,因此您需要将值转换为其实际类型。根据您的工作表,这可能是浮点数或字符串:

let firstTitle = vals.[1, 1] :?> string
let firstValue = vals.[2, 1] :?> float

(Assuming you have a title in A1 and a number in A2)

(假设您在A1中有一个标题,在A2中有一个数字)

#1


3  

The type of Value2 is obj. If the range represents just a single cell, the actual type will be some primitive type (int, float, decimal, string). If the range represents several cells (your case), then the returned value is a two-dimensional .NET array of type obj[,].

对象2的类型是obj。如果范围仅表示单个单元格,则实际类型将是某种基本类型(int,float,decimal,string)。如果范围代表几个单元格(您的情况),则返回的值是obj [,]类型的二维.NET数组。

You can cast the value returned by Value2 to an array and access it using indexers:

您可以将Value2返回的值强制转换为数组并使用索引器访问它:

let vals = sheet.UsedRange.Value2 :?> obj[,]
vals.[1, 1]

Note that the returned array is 1-based (and not zero based as usual). The indexer again returns obj, so you need to cast the values to their actual type. Depending on your sheet, this will be probably float or string:

请注意,返回的数组是基于1的(并且不像通常那样基于零)。索引器再次返回obj,因此您需要将值转换为其实际类型。根据您的工作表,这可能是浮点数或字符串:

let firstTitle = vals.[1, 1] :?> string
let firstValue = vals.[2, 1] :?> float

(Assuming you have a title in A1 and a number in A2)

(假设您在A1中有一个标题,在A2中有一个数字)