I am trying to process data in an Excel worksheet passed from a C# class to an F# class library.
The C# project is an Excel AddIn project the F# class is this.
namespace DataLib
open System
open System.Reflection
open System.Collections.Generic
open FSharpx.TypeProviders.Excel
open Microsoft.FSharp.Core.CompilerServices
open System.IO
open System.Linq
open System.Text
open System.Windows.Forms
open Microsoft.Office.Core
open Microsoft.Office.Interop.Excel
open Microsoft.Office.Tools.Excel
type sheet = Microsoft.Office.Interop.Excel.Worksheet
type Class1() =
member this.X = "F#"
member this.Readsheet (sh:obj)=
let sht = sh:?>Worksheet// exception here
let v=sh.Cells.[1,1] // Exception COM object does not have Cells property etc...
sh.Range.Item(1,1).ToString() //error here ca
So if I call the class from C# like this
using DataLib;
public void useExcel(sh as Excel.Worksheet) //Excel.Worksheet is Excel Interop object
{
Class1 one = new Class1()
one.Readsheet(sh) //Exception thrown here in F# class
}
Interop between F# and C# isn’t a problem. You have various errors in your F# class:
You cast an Object
shto Worksheetsht, but mistakenly useshinstead ofshtlater.Rangedoesn’t haveItemproperty.You add virtually everything related to Excel programming into the project. You only need
Microsoft.Office.Interop.Excelin this example. It’s better to remove unnecessaryopencommands, especiallyMicrosoft.Office.Tools.Excelwhich is opened afterInterop.Excelcould have objects of the same names but have incompatible fields/interfaces.You should pass a
Worksheetinstead of anobjto avoid downcasting.A minimal F# example that works:
Moreover, your C# syntax is a bit off, you need something like: