简体   繁体   English

F#将行动态插入Excel

[英]F# insert row into Excel dynamically

I need to insert rows in excel dynamically. 我需要在Excel中动态插入行。 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. 我想从一行开始(第17行)开始复制n次事务。

Can anyone shed any light on doing this in F#? 谁能在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. 我不一定会推荐这种方法,但是如果您可以通过F#的dynamic运算符可以在此处找到其实现)来 动态解释,那么您可以在不参考任何特定库的情况下进行Interop。

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()

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

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