首页 > 解决方案 > 无法使用 OpenXml 从 F# 中的 Excel 文件中读取

问题描述

我试图弄清楚如何使用 F# 从现有的 Excel 文件中读取数据。我发现了这个(相当老的)问题,但运行它时遇到问题: Reading cell contents in an Excel file with F# and Open XML SDK

似乎编译器或 SDK(或两者)在这一行方面发生了变化:

let theSheet:Worksheet = ((WorksheetPart.wbPart.GetPartById(firstSheet.Id)).Worksheet

(我知道括号中有错字;只是想引用原始来源)

即使没有额外的括号和以下代码:

// Learn more about F# at http://fsharp.org

open System
open System.Linq
open System.Data
open System.Windows
open DocumentFormat.OpenXml // Also install DocumentFormat.OpenXml from nuget
open DocumentFormat.OpenXml.Packaging
open DocumentFormat.OpenXml.Spreadsheet
open Microsoft.Office.Interop.Excel

let toStr s = Printf.TextWriterFormat<unit>(s)

//Read the value of a single cell by string coordinates (Open XML SDK)
let read_value_openxml (file_path_and_name:string) (column:int) (row:int):string =
    let stream = new System.IO.FileStream(file_path_and_name, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite)

    // Open the spreadsheet document for read-only access.
    let document = SpreadsheetDocument.Open(stream, false)

    // Retrieve a reference to the workbook part.
    let wbPart = document.WorkbookPart

    // Find the sheet with the supplied name, and then use that sheet object to retrieve a reference to the first worksheet.
    let firstSheet:Sheet = wbPart.Workbook.Descendants<Sheet>().Where(fun s -> (toStr s.Name.Value).Equals("Sheet1")).First()


    // Retrieve a reference to the worksheet part.
    let wsPart:Worksheet = wbPart.GetPartById(firstSheet.Id.ToString())

    // Use its Worksheet property to get a reference to the cell whose address matches the address you supplied.
    let theCell = wsPart.Worksheet.Descendants<Cell>().Where(fun c -> c.CellReference = column + row).FirstOrDefault()

    "test"

编译器抱怨该行

let wsPart:Worksheet = wbPart.GetPartById(firstSheet.Id.ToString())

这么说

Severity    Code    Description Project File    Line    Suppression State
Error   FS0001  This expression was expected to have type
    'Worksheet'    
but here has type
    'OpenXmlPart'   HelloF  C:\Users\user\Documents\workspace\FSharp\HelloF\HelloF\Program.fs   32  Active

我也尝试将值显式OpenXmlPart转换为Worksheet

let ws:Worksheet = (wbPart.GetPartById(firstSheet.Id.ToString()):OpenXmlPart) :?> Worksheet

虽然结果相同。

所以我在 SDK 文档中查找了这个问题,它提供了以下示例代码(在 VB 中)

...
' Reference to Excel Worksheet with Customer data. 
custID = _
   workSheets.First(Function(sheet) sheet.Name = "Customer").Id()
aacustSheet = DirectCast( _
   document.WorkbookPart.GetPartById(custID), WorksheetPart)

这里 aDirectCast用于这部分代码。

在 F# 中使用此 SDK 的正确方法是什么?我找到了几个关于如何通过创建新的 WorkBookParts 来创建新的 Excel 文件的示例,但不幸的是,没有仅用于阅读的工作示例。

标签: excelf#openxml-sdk

解决方案


您是否考虑过 Excel 类型提供程序?

https://fsprojects.github.io/ExcelProvider/


推荐阅读