4

I have an Excel workbook of which I want to edit/fill some particular cells using R, without changing any of the formatting.

So far I've tried XLConnect package and it seems it could do what I'm looking for, I just didn't find a way to do it.

My straightforward approach to the problem:

wb <- loadWorkbook("file1.xls")
data1 <- readWorksheet(wb, "Sheet1", header=TRUE)

## adding a value to a particular cell:
data1[11,12] <- 3.2 

## rewriting old data:
writeWorksheet(wb, data1, "Sheet1")
saveWorkbook(wb, "new_file1.xls")

However, this way the new workbook loses all of the previous formatting (merged cells, formulas, etc).

Is there a way to change values in some of the cells without losing any of the formatting of the remaining sheet?

4

3 回答 3

9

这是一个使用 R 自动化 Excel 的示例。

library(RDCOMClient)
xlApp <- COMCreate("Excel.Application")
wb    <- xlApp[["Workbooks"]]$Open("file.1.xls")
sheet <- wb$Worksheets("Sheet1")

# change the value of a single cell
cell  <- sheet$Cells(11,12)
cell[["Value"]] <- 3.1

# change the value of a range
range <- sheet$Range("A1:F1")
range[["Value"]] <- paste("Col",1:6,sep="-")

wb$Save()                  # save the workbook
wb$SaveAS("new.file.xls")  # save as a new workbook
xlApp$Quit()               # close Excel
于 2014-11-14T20:36:33.383 回答
4

使用XLC$STYLE_ACTION.NONE样式操作应该在不更改任何格式的情况下添加您的数据:

data1 <- readWorksheetFromFile("file1.xls", "Sheet1")

## adding a value to a particular cell:
data1[11,12] <- 3.2 

## rewriting old data:
writeWorksheetToFile("file1.xls", data1, "Sheet1", styleAction = XLC$STYLE_ACTION.NONE)

感谢 Martin 建议在评论中对此进行调查。

于 2016-05-27T22:24:26.717 回答
4

如果您不需要使用公式,您有 2 种可能的解决方案。

您可以使用 {xlsx} 包:

library(xlsx)
xlsx::write.xlsx(x = head(iris),file = "source3.xlsx",sheetName = "A")
hop3 <- xlsx::loadWorkbook(file = "source3.xlsx")
sheets <- getSheets(hop3)
rows  <- getRows(sheets$A,rowIndex = 2)   # get all the rows
cc <- getCells(rows,colIndex = 3) 
xlsx::setCellValue(cc[[1]],value = "54321")
hop3$setForceFormulaRecalculation(TRUE)
xlsx::saveWorkbook(hop3,file = "output3.xlsx")

您也可以使用 {XLconnect}

library(XLConnect)    
XLConnect::writeWorksheetToFile(file = "source2.xlsx",data = head(iris),sheet="A")
hop2 <- XLConnect::loadWorkbook(file = "source2.xlsx")
createName(hop2, name = "plop", formula = "A!C2")
writeNamedRegion(hop2, 12345, name = "plop", header = FALSE)

问候

于 2019-03-05T08:46:35.603 回答