Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I modify an existing a sheet in an Excel Workbook using Openxlsx package in R?

Tags:

r

excel

openxlsx

I am using "openxlsx" package to read and write excel files. I have a fixed file with a sheet called "Data" which is used by formulas in other sheets. I want to update this Data sheet without touching the other. I am trying the following code:

write.xlsx(x = Rev_4, file = "Revenue.xlsx", sheetName="Data") 

But this erases the excel file and creates a new one with just the new data in the "Data" sheet while all else gets deleted. Any Advice?

like image 248
Nipun Arora Avatar asked Dec 09 '15 06:12

Nipun Arora


People also ask

How do you write into an existing Excel file in R?

To write to an existing file, use write. xlsx() method and pass the data in the form of matrix or data frame. Notice that the write. xlsx() function prepends each row with a row name by default.

Can existing files in Excel be modified?

As such you cannot simply append or update an Excel file. The only way to achieve this is to read the entire file into memory, make the required changes or additions and then write the file out again.

How do I add data to an existing worksheet in Excel?

Enter text or a number in a cellOn the worksheet, click a cell. Type the numbers or text that you want to enter, and then press ENTER or TAB. To enter data on a new line within a cell, enter a line break by pressing ALT+ENTER.


1 Answers

Try this:

wb <- loadWorkbook("Revenue.xlsx") writeData(wb, sheet = "Data", Rev_4, colNames = F) saveWorkbook(wb,"Revenue.xlsx",overwrite = T) 

You need to load the complete workbook, then modify its data and then save it to disk. With writeData you can also specify the starting row and column. And you could also modify other sections before saving to disk.

like image 65
R. Schifini Avatar answered Sep 20 '22 19:09

R. Schifini