我正在尝试使用.xlsx
中的openxlsx
包从R
文件中读取值。简单来说,我需要写一行数据,然后填充一些必须在R中读回的输出单元格。我将分享一个例子来更好地解释这个问题。
.xlsx
文件的初始状态:
我现在正在尝试向单元格写入新值:A2:A3 = c(“c”,5)。理想情况下,我期待A6 = 15
以下是使用的代码:
require(openxlsx)
path <- "C:/path_to_file/for_SO1.xlsx"
input_row <- c("c", 5)
# Load workbook; create if not existing
wb <- loadWorkbook(path)
# createSheet(wb, name = "1")
writeData(wb,
sheet = "Sheet1",
x = data.frame(input_row),
startCol=1,
startRow=1
)
data_IM <- read.xlsx(wb,
sheet = "Sheet1",
rows = c(5,6),
cols = c(1))
# Save workbook
saveWorkbook(wb, file = path, overwrite = TRUE)
#> data_IM
# output_row
#1 3
但我得到了初始值(3)。但是,如果我打开.xlsx
文件,我可以看到驻留在那里的15
:
无法读取此单元格的原因是什么?在写入文件并再次阅读之后我尝试保存它,但即便失败也是如此。由于XLConnect等的JAVA错误,openxlsx
是我唯一的选择。
答案 0 :(得分:2)
?read.xlsx
使用writeFormula写入Workbook对象的公式将无法获取 由read.xlsx()获取。这是因为只写了公式 并在Excel中打开文件时进行评估。开幕 使用Excel保存和关闭文件将解决此问题。
因此需要在Excel中打开文件然后保存,我可以验证这确实有效。但是,这可能不适合你。
XLConnect
似乎具有所需的功能
# rjava can run out of memory sometimes, this can help.
options(java.parameters = "-Xmx1G")
library(XLConnect)
file_path = "test.xlsx"
input_row <- c("c", 5)
wb <- loadWorkbook(file_path, create=F)
writeWorksheet(wb, 1, startRow = 1, startCol = 1, data = data.frame(input_row))
setForceFormulaRecalculation(wb, 1, TRUE)
saveWorkbook(wb)
# checking
wb <- loadWorkbook(file_path, create=F)
readWorksheet(wb, 1)
答案 1 :(得分:0)
文件https://cran.r-project.org/web/packages/openxlsx/openxlsx.pdf说
readbook.xlsx()不会拾取工作簿对象。 这是因为在Excel中打开文件时,仅编写公式并留待评估。 使用Excel打开,保存和关闭文件将解决此问题。 因此,如果您使用的是Windows, 将以下文件vbs文件保存到例如opensaveexcel.vbs
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("D:\Book2.xlsx")
objWorkbook.Save
objWorkbook.Close
objExcel.Quit
Set objExcel = Nothing
Set objWorkbook = Nothing
然后您可以编写R代码,因为单元格A4在Book1.xlsx中的公式为= A3 * 5
mywritexlsx(fname="d:/Book1.xlsx",data = 20,startCol = 1,startRow = 3)
system("cp d:\\Book1.xlsx d:\\Book2.xlsx")
system("cscript //nologo d:\\opensaveexcel.vbs")
tdt1=read.xlsx(xlsxFile = "d:/Book1.xlsx",sheet = "Sheet1",colNames = FALSE)
tdt2=read.xlsx(xlsxFile = "d:/Book2.xlsx",sheet = "Sheet1",colNames = FALSE)
以mywritexlsx的方式为我工作
mywritexlsx<-function(fname="temp.xlsx",sheetname="Sheet1",data,
startCol = 1, startRow = 1, colNames = TRUE, rowNames = FALSE)
{
if(!file.exists(fname))
{
wb = openxlsx::createWorkbook()
sheet = openxlsx::addWorksheet(wb, sheetname)
}
else
{
wb <- openxlsx::loadWorkbook(file =fname)
if(!(sum(openxlsx::getSheetNames(fname)==sheetname)))
sheet = openxlsx::addWorksheet(wb, sheetname)
else
sheet=sheetname
}
openxlsx::writeData(wb,sheet,data,startCol = startCol, startRow = startRow,
colNames = colNames, rowNames = rowNames)
openxlsx::saveWorkbook(wb, fname,overwrite = TRUE)
}