editing particular cells of an Excel sheet

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?


这里是一个使用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

Using the XLC$STYLE_ACTION.NONE style action should add your data without changing any formatting:

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)

Thanks to Martin for the suggestion to look into this in the comments.

链接地址: http://www.djcxy.com/p/27764.html

上一篇: 如何使用开放XML在Excel中格式化单元格

下一篇: 编辑Excel工作表的特定单元格