简体   繁体   English

F#将Excel文件解析为元组数组

[英]F# Parse Excel File Into Tuple Array

I have a follow up question on this post. 对此帖子有后续问题。 I would like to take the contents of an Excel spreadsheet and put it into a Array of tuples where each tuple corresponds to each row in the spreadsheet. 我想将Excel电子表格的内容放入一个元组数组,其中每个元组对应于电子表格中的每一行。

I started with looping though the entire range like this: 我从遍历整个范围开始,如下所示:

    let path = "XXX.xlsx"
    let app = ApplicationClass(Visible = false)
    let book = app.Workbooks.Open path
    let sheet = book.Worksheets.[1] :?> _Worksheet
    let content = sheet.UsedRange.Value2 :?> obj[,]
    for i=content.GetLowerBound(0) to content.GetUpperBound(0) do
        for j=content.GetLowerBound(1) to content.GetUpperBound(1) do

But strikes me as very inefficient. 但是让我觉得效率很低。 If there something in the base API spec out of the box that I can use? 如果我可以使用基本API规范中的某些可用内容?

Thanks in advance 提前致谢

The Array2D module implements some common functions for 2D arrays. Array2D模块为2D阵列实现一些常用功能。

I am guessing you want to use Array2D.iter or Array2D.iteri to replace your for loop. 我猜您想使用Array2D.iterArray2D.iteri替换您的for循环。

The straightforward way to convert each row (of a two-dimensional array) to a tuple (in a single-dimensional row) is to finish what you started - just iterate over all the rows and construct a tuple: 将每行(二维数组)转换为元组(在单维行中)的直接方法是完成开始的工作-只需遍历所有行并构造一个元组:

let tuples = 
  [ for i in contents.GetLowerBound(0) .. contents.GetUpperBound(0) -> 
      contents.[i,0], contents.[i,1], contents.[i,2] ]

To do this, you need to know (statically) what is the length of the row. 为此,您需要(静态地)知道行的长度。 This is because F# tuples are fixed-length tuples and the length is checked. 这是因为F#元组是固定长度的元组,并且检查了长度。 The above example assumes that there are just 3 elements with indices 0 , 1 and 2 . 上面的例子中假定存在仅有3具有索引元素012 If the length is dynamic, then you probably should continue using 2D arrays rather than a list of tuples. 如果长度是动态的,那么您可能应该继续使用2D数组而不是元组列表。

Another option is to bypass the Excel engine altogether. 另一个选择是完全绕过Excel引擎。 There are a couple of ways of doing this, but the one I've had great success with is 'SpreadsheetGear'. 有两种方法可以做到这一点,但是我获得了巨大成功的是“ SpreadsheetGear”。 It isn't free (bring on the downvotes), but it replicates the Excel API very closely and is very fast. 它不是免费的(减少票数),但是它非常紧密且快速地复制了Excel API。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM