F#读取XLS文件 - 如何分析一个值2对象对象、文件、XLS

由网友(粨毐不侵)分享简介:我试图用F#读取xls文件如下开放的Microsoft.Office.Interop.Excel让应用程序= ApplicationClass(可见= FALSE)让书= app.Workbooks.OpenTEST.XLS让片= book.Worksheets [1]:>。? _Worksheet让瓦尔...

我试图用F#读取xls文件如下

 开放的Microsoft.Office.Interop.Excel
让应用程序= ApplicationClass(可见= FALSE)
让书= app.Workbooks.OpenTEST.XLS
让片= book.Worksheets [1]:>。? _Worksheet
让瓦尔斯= sheet.UsedRange.Value2
 

现在的问题是我怎么能解析丘壑成F#类型?在fsx.exe中,丘壑表现为

 VAL瓦尔斯:OBJ = [bound1
                  bound2
                  [colname1; colname2; ...]
                  [1234,5678,] ...]
 

我想首先检索该字符串重新presetation,但 printfn%Avals.ToString();; 节目System.Object的[,]只。如果我再尝试访问丘壑。[1,1] ,我得到了错误字段,构造或成员项没有定义

感谢

解决方案

值2 的类型是 OBJ 。如果范围再presents只是一个单细胞,实际的类型也会有一些基本类型(整数,浮点,十进制,字符串)。如果范围再presents几个小区(你的情况),则返回值的类型的二维数组.NET的obj [,]

2.数据驱动测试 适合UI 接口自动化

您可以投值2 将其使用索引数组和访问返回的值:

 让瓦尔斯= sheet.UsedRange.Value2:>? OBJ [,]
瓦尔斯[1,1]
 

请注意,返回的数组是从1开始的(而不是基于零像往常一样)。索引器再次返回 OBJ ,所以你需要转换值,以自己的实际类型。根据您的工作表,这很可能是浮动或字符串:

让firstTitle =丘壑[1,1]:>串 让firstValue =丘壑[2,1]。?>浮动

(假设你已经在A1中一个标题和一个数字A2)

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

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 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

thanks,

解决方案

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[,].

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

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:

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

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

阅读全文

相关推荐

最新文章