简体   繁体   中英

How do I modify an existing sheet in Excel using openxlsx (with same lay-out)?

Lets say I create the following Excel file:

library(openxlsx)
library(writexl)

writexl::write_xlsx(list(iris = iris, mtcars = mtcars), "example_modify_exceltab.xlsx")

Then I would like to modify an existing sheet in this file. I use the answer from the following question: How do I modify an existing a sheet in an Excel Workbook using Openxlsx package in R?

wb <- loadWorkbook("example_modify_exceltab.xlsx")

Then I add a sheet with data 'USArrests':

addWorksheet(wb, sheetName = "USArrests")
writeData(wb, sheet = "USArrests", USArrests, colNames = TRUE)

Save workbook:

saveWorkbook(wb, "example_modify_exceltab1.xlsx", overwrite = TRUE)

The problem now is that the data in file example_modify_exceltab.xlsx has column names, and the column names in 'example_modify_exceltab1.xlsx' are empty. I would like to achieve that the sheets iris and mtcars still have the same column names as in example_modify_exceltab.xlsx . How do I achieve this using openxlsx ?

it seems to be related to the use of the two packages together, even if you save before adding the new sheet the headers are missing.

But you can use write.xls from openxlsx package and it works fine, just change this line:

writexl::write_xlsx(list(iris = iris, mtcars = mtcars), "example_modify_exceltab.xlsx")

to:

openxlsx::write.xlsx(list(iris = iris, mtcars = mtcars), "example_modify_exceltab.xlsx")

and your script will run as intended

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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