I need to insert rows in excel dynamically. I am generating an invoice which can have a varied number of transactions and their for require a row for each transaction.
I want to start with one row (row 17) and duplicate it for n number of transactions.
Can anyone shed any light on doing this in F#?
I wouldn't necessarily recommend this approach, but if you're ok with dynamically being interpreted as by means of F#'s dynamic operator ( an implementation of which can be found here ), then you can do Interop without any reference to a specific library.
let xlApp = System.Runtime.InteropServices.Marshal.GetActiveObject "Excel.Application"
let rng : obj = xlApp?ActiveWorkbook?ActiveSheet?Rows(17)
rng?Copy()
rng?Insert()
That is, copy a row to the clipboard, and insert it at the same position.
Edit
It turns out that many Reflection-based definitions of the dynamic operator aren't suited to interop, including the one linked above. Supplying my own:
let (?) (o: obj) name : 'R =
let bindingFlags = System.Reflection.BindingFlags.GetProperty
let invocation args =
o.GetType().InvokeMember(name, bindingFlags, null, o, args)
let implementation args =
let argType, resType = FSharpType.GetFunctionElements typeof<'R>
if argType = typeof<unit> then [| |]
elif FSharpType.IsTuple argType then FSharpValue.GetTupleFields args
else [| args |]
|> invocation
|> fun res -> if resType = typeof<unit> then null else res
if FSharpType.IsFunction typeof<'R> then
FSharpValue.MakeFunction(typeof<'R>, implementation)
else invocation null
|> unbox<'R>
We can now define a function in order to insert a variable number of copied rows.
let copyAndInsertRow17 n =
if n > 0 then
let xlApp =
System.Runtime.InteropServices.Marshal.GetActiveObject "Excel.Application"
let sheet = xlApp?ActiveWorkbook?ActiveSheet
sheet?Rows(17)?Copy()
sheet?Range(sheet?Rows(17 + 1), sheet?Rows(17 + n))?Insert()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.