使用XLConnect的appendWorksheet函数向现有Excel表添加新行

时间:2017-12-14 21:26:06

标签: r excel

我想要实现的是将bool verbose = false; var template = verbose ? "{Timestamp:HH:mm:ss} [{Level:u3}] {Message}{NewLine}{Exception}" : "{Message}{NewLine}"; Log.Logger = new LoggerConfiguration() .WriteTo.Console(outputTemplate: template, theme: SystemConsoleTheme.Grayscale) .CreateLogger(); 中的对象中的一行添加到theme文件中已存在的表中(如“Excel表格中的读表”)。

使用以下代码,我将该行完美地添加到现有表中:

R

这里的问题是我在Excel中使用引用作为Excel获得了大量其他公式。如果我添加行,则值将不会自动成为library(XLConnect) setStyleAction(wb,XLC$"STYLE_ACTION.NONE") wb <- loadWorkbook("test.xlsx") appendWorksheet(wb, expense, sheet="expenses", header = FALSE) saveWorkbook(wb) 表的一部分。这可能吗?

1 个答案:

答案 0 :(得分:1)

我建议在电子表格中编写一个简单的公式复制宏。当然,您需要将其称为test.xlsm而不是test.xlsx。如果您的电子表格如下所示:

enter image description here

然后您的宏可能如下所示:

Option Explicit

Sub MyMacro()
    Dim BottomRowOfData As Integer, BottomRowOfFormula As Integer, rowDiff As Integer

    With ThisWorkbook.Worksheets("expenses")
        BottomRowOfData = .Range("B1").End(xlDown).Row
        BottomRowOfFormula = .Range("C1").End(xlDown).Row
        rowDiff = BottomRowOfData - BottomRowOfFormula

        If (rowDiff > 0) Then
            .Range("C" & BottomRowOfFormula).Copy
            Call .Range(.Range("C" & BottomRowOfFormula + 1), .Range("C" & BottomRowOfData)).PasteSpecial
        End If
    End With

    ' Save your work
    ThisWorkbook.Save
End Sub

根据我对this question on so的回答,您可以从R调用VBA宏。为了完整起见,这里是该问题的代码:

library(RDCOMClient)

# Open a specific workbook in Excel:
xlApp <- COMCreate("Excel.Application")
xlWbk <- xlApp$Workbooks()$Open("C:\\TEMP\\test.xlsm")

# this line of code is only necessary if you want to see your spreadsheet getting updated:
xlApp[['Visible']] <- TRUE 

# Run the macro called "MyMacro":
xlApp$Run("MyMacro")

# Close the workbook and quit the app:
xlWbk$Close(FALSE)
xlApp$Quit()

# Release resources:
rm(xlWbk, xlApp)
gc()