f# 读取 xls 文件 - 如何解析 value2 对象 [英] f# read xls file - how to parse a value2 object

查看:15
本文介绍了f# 读取 xls 文件 - 如何解析 value2 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我想先检索字符串表示,但是printfn "%A" vals.ToString();; 仅显示 "System.Object[,]".如果我然后尝试访问 vals.[1,1],我得到错误 The field,constructor or member 'item' is not defined

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

谢谢,

推荐答案

Value2 的类型是 obj.如果范围仅表示单个单元格,则实际类型将是某种原始类型(int、float、decimal、string).如果范围表示多个单元格(您的情况),则返回值是 obj[,] 类型的二维 .NET 数组.

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

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

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]

请注意,返回的数组是从 1 开始的(而不是像往常一样从零开始).索引器再次返回 obj,因此您需要将值转换为它们的实际类型.根据您的工作表,这可能是浮点数或字符串:

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

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

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

这篇关于f# 读取 xls 文件 - 如何解析 value2 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆