2

I have a data frame e.g.

a=1:10 
b=31:40
c=data.frame(a=a,b=b)

and I will need to write this data frame into a specific Excel sheet ("Sheet1").

I am using WriteXLS now but this function always overrides the entire excel file and thus deletes other sheets. How can I append to the sheet without overwriting previous entries?

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138
SilverSpoon
  • 655
  • 4
  • 8
  • 17
  • 1
    possible duplicate of [Read an Excel file directly from a R script](http://stackoverflow.com/questions/6099243/read-an-excel-file-directly-from-a-r-script) – joran Mar 01 '13 at 05:46
  • The above-linked question is technically about reading, not writing, Excel files, but the tools used are the same. – joran Mar 01 '13 at 05:46
  • i have no problem reading from a specific sheet and writing to excel. But writing to a specific sheet in excel is puzzling me. – SilverSpoon Mar 01 '13 at 05:58
  • `writeWorksheet` in the `XLConnect` package sounds like it'll do the trick – Ben Mar 01 '13 at 06:00
  • Which is precisely why I pointed you towards the tools that allow you to do that. – joran Mar 01 '13 at 06:01

3 Answers3

3

This will add a new named sheet to an existing Excel workbook without altering existing sheets:

# create data in R
a = 1:10 
b = 31:40
c0 = data.frame(a=a,b=b)

#  write data object 'c0' to existing Excel file 
# 'Book1.xlsx' into a new sheet called 'Sheet1'
library(XLConnect)
writeWorksheetToFile(file = "C:/.../Book1.xlsx", data = c0, sheet = "Sheet1")

Note that if the workbook already has a Sheet1 then this function would silently overwrite it. So you'll need to make sure your sheet names are unique.

Ben
  • 41,615
  • 18
  • 132
  • 227
2

Try with xlsx package. You have the function write.xlsx() which allows you to specify a name sheet and you can complete an existing excel.

jmanelsg
  • 154
  • 1
  • 3
0

You can simply write into a new sheet of an existing Excel file without modifiying the existing sheets or any other information by doing it this way:

library(xlsx)
a=1:10 
b=31:40
c=data.frame(a=a,b=b)

write.xlsx(c, "existing_Excel_file.xlsx", sheetName="New sheet name",  append=TRUE)

Remember to set the append argument of write.xlsx to TRUE and make sure the Excel file you are writing in to is in your current working Directory.

Charles
  • 161
  • 12