简体   繁体   English

使用 write.xlsx 用 R 包 xlsx 替换现有工作表

[英]Using write.xlsx to replace an existing sheet with R package xlsx

I am using package xlsx Version:0.5.7 Date: 2014-08-01.我正在使用包xlsx版本:0.5.7 日期:2014-08-01。 in R version 3.0.1 (2013-05-16) -- "Good Sport" Platform: i386-w64-mingw32/i386 (32-bit).在 R 版本 3.0.1 (2013-05-16) 中——“Good Sport”平台:i386-w64-mingw32/i386(32 位)。

I have an xlsx file with at least 2 sheets (say A and B).我有一个至少有 2 张纸的 xlsx 文件(比如 A 和 B)。 I need to read data from A, edit them and save them in B. This has to be done on a periodical base.我需要从 A 读取数据,编辑它们并将它们保存在 B 中。这必须在期刊基础上完成。

I am able to read data from A with read.xlsx .我可以使用read.xlsx从 A 读取数据。 After editing the data frame I want to save it in an existing sheet B in the same xlsx file.编辑数据框后,我想将其保存在同一个 xlsx 文件中的现有工作表 B 中。

I try with this line我试着用这条线

write.xlsx(down, paste0(root,'/registration reports/registration complete_WK.xlsx'), sheet="data_final", col.names=T, row.names=F, append=T, showNA=F)

but it give me this error:但它给了我这个错误:

Error in `.jcall(wb, "Lorg/apache/poi/ss/usermodel/Sheet;", "createSheet", ` : 
  java.lang.IllegalArgumentException: The workbook already contains a sheet of this name

I need to replace that existing sheet multiple times.我需要多次替换现有的工作表。 How can I do that?我怎样才能做到这一点?

If you want to save your new dataframe in an existing excel file, you first have to load the xlsx-file:如果要将新数据框保存在现有 excel 文件中,首先必须加载 x​​lsx 文件:

wb <- loadWorkbook(file)

which sheets you have you'll get like this:你有哪些床单,你会得到这样的:

sheets <- getSheets(wb)

you can easily remove and add (and thus replace) sheets with:您可以轻松地删除和添加(从而替换)工作表:

removeSheet(wb, sheetName="Sheet1")
yourSheet <- createSheet(wb, sheetName="Sheet1")

than you can fill the sheets with dataframes:比你可以用数据框填充工作表:

addDataFrame(yourDataFrame, yourSheet, <options>)
addDataFrame(anotherDataFrame, yourSheet, startRow=nrow(yourDataFrame)+2)

and last step is saving the whole workbook as .xlsx:最后一步是将整个工作簿保存为 .xlsx:

saveWorkbook(wb, file)

btw: the documentation of the xlsx-package is really good and helpful on such questions :) http://cran.r-project.org/web/packages/xlsx/xlsx.pdf顺便说一句:xlsx-package 的文档非常好,对此类问题很有帮助:) http://cran.r-project.org/web/packages/xlsx/xlsx.pdf

It may be that the Java installed on your computer is incompatible with the xlsx library.可能是您计算机上安装的 Java 与 xlsx 库不兼容。 The following thread discusses a similar issue with regard to the same package: enter link description here以下线程讨论了关于同一个包的类似问题: 在此处输入链接描述

Alternatively, your issue may be solved by a different Excel-related package, such as XLConnect.或者,您的问题可以通过不同的 Excel 相关包解决,例如 XLConnect。 See this post: enter link description here请参阅此帖子: 在此处输入链接描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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