Skip to content

Instantly share code, notes, and snippets.

@fbmnds
Created November 28, 2013 09:04
Show Gist options
  • Select an option

  • Save fbmnds/7689096 to your computer and use it in GitHub Desktop.

Select an option

Save fbmnds/7689096 to your computer and use it in GitHub Desktop.
/// be explicite: path might be None (pseudo overloading)
type ExcelWorkbook(path: string option, fname: string) =
/// should be a singleton shared by workbooks?
let excel = getExcel()
let fqn =
match path with
| Some path -> path+"\\"+fname
| _ -> System.Environment.CurrentDirectory+fname
let workbooks =
match excel with
| Some excel -> getWorkbooks excel
| _ -> None
let workbook =
match workbooks with
| Some workbooks -> getWorkbook workbooks fqn
| _ -> None
let sheets =
match workbook with
| Some workbook -> Some workbook.Sheets
| _ -> None
/// would want to manage an array of sheet(s) ?
let mutable sheet = None
/// Finally destilled from:
/// http://stackoverflow.com/questions/158706/how-to-properly-clean-up-excel-interop-objects
/// http://stackoverflow.com/questions/19977337/closing-excel-application-with-excel-interop-without-save-message
/// http://msdn.microsoft.com/en-us/library/h1e33e36.aspx
member x.close() =
match workbook with | Some workbook -> trySave(workbook) | _ -> ignore workbook
/// may release None:
releaseComObject sheet |> ignore
releaseComObject sheets |> ignore
releaseComObject workbook |> ignore
match workbooks with | Some workbooks -> workbooks.Close() | _ -> ignore workbooks
releaseComObject workbooks |> ignore
match excel with | Some excel -> excel.Quit() | _ -> ignore excel
releaseComObject excel |> ignore
/// Expert F# 3.0, p. 139
interface System.IDisposable with
member x.Dispose() = x.close()
member x.setSheetByName name =
match sheets with
| Some (sheets) -> sheet <- Some(getSheetByName sheets name)
| _ -> ignore name
member x.setSheetByIndex idx =
match sheets with
| Some (sheets) -> sheet <- Some (getSheetByIndex sheets idx)
| _ -> ignore idx
member x.getFrameWithStringHeader (ul: int*int) (lr: int*int) =
match sheet with
| Some sheet -> getFrameWithStringHeader sheet ul lr
| _ -> None
member x.getRangeAsArray ulrow ulcol lrrow lrcol : Array option =
match sheet with
| Some sheet -> getRangeAsArray sheet ulrow ulcol lrrow lrcol
| _ -> None
member x.getFrameWithHeader ulrow ulcol lrrow lrcol : Frame<int,_> option =
match sheet with
| Some sheet -> getFrameWithHeader sheet ulrow ulcol lrrow lrcol
| _ -> None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment