XLConnect - 带有循环对象的readWorksheet

时间:2015-05-15 15:22:09

标签: r for-loop xlconnect

我正在使用带有XLConnect包的R Studio 3.1.2版来加载,读取和写入多个xlsx文件。我可以通过复制和创建多个对象来执行此操作,但我尝试使用1个对象(同一文件夹中的所有文件)执行此操作。请看例子 我可以这样做列出每个文件,但希望使用循环

Sub ReportStuff()

    Dim oSl As Slide
    Dim oSh As Shape

    Set oSl = SlideShowWindows(1).View.Slide

    ' Test to see if the shape's already there:
    Set oSh = IsItThere(oSl, "My Text Box")

    ' If it's not there, add it:
    If oSh is Nothing Then
       Set oSh = oSl.Shapes.AddTextbox(msoTextOrientationHorizontal, 100, 100, 200, 50)
       oSh.Name = "My Text Box"
    End If

    With oSh.TextFrame.TextRange
        .Text = "Index: " & oSl.SlideIndex & " ID: " & oSl.SlideID & " File: " & ActivePresentation.FullName
    End With

End Sub

Function IsItThere(oSl as Slide, sName as String) as Shape
   Dim oSh as Shape
   For each oSh in oSl.Shapes
      If oSh.Name = sName Then
         Set IsItThere = oSh
         Exit Function
      End If
   Next
End Function

这是我试图这样做但却出错的方式

tstA <- loadWorkbook("\\\\FS01\\DEPARTMENTFOLDERS$\\tst\\2015\\Apr\\DeptA.xlsx")
tstB <- loadWorkbook("\\\\FS01\\DEPARTMENTFOLDERS$\\tst\\2015\\Apr\\DeptB.xlsx")

在此之后我想使用XLConnect的readWorksheet函数。

为蹩脚的问题道歉,但我正在努力锻炼如何最好地做到这一点。 感谢

1 个答案:

答案 0 :(得分:2)

您可以在一个操作中将所有文件读入列表,如下所示(根据需要调整patternsheet以获取所需的文件/表格):

path = "\\\\FS01\\DEPARTMENTFOLDERS$\\tst\\2015\\Apr\\"

df.list = lapply(list.files(path, pattern="xlsx$"), function(i) {
  readWorksheetFromFile(paste0(path, i), sheet="YourSheetName")
})

如果要将所有数据帧合并为一个数据框,可以执行以下操作:

df = do.call(rbind, df.list)