提问人:Bambeil 提问时间:11/8/2023 更新时间:11/8/2023 访问量:43
使用 xlsx 包 saveWorkbook() 函数保存后,Excel 中的数字格式错误
Wrong numbers format in Excel after saving with xlsx package saveWorkbook() function
问:
我有很长的代码,它需要什么 excel 工作簿,其中包含几张工作表,已经应用的样式,格式和宏。在我的代码中,我将数据添加到特定的单元格(以矩阵的形式),主要是数字,但也有一些文本,然后保存在新的 excel 文件中。我面临的问题是,在保存的工作簿中,数字不会另存为数字 - 例如,15或0不被视为数字 - 只有在我在excel单元格中按Enter键后,它们才会转换为数字。此外,更大的问题是,由于某种原因,小数是用点而不是逗号保存的,例如,R 中的 1.5151,而不是 1,5151 - 即使在 R 代码中数据类型确实是数字。如果只保存随机数据帧以分离 excel,则数字应有尽有。简短的演示示例:
### read empty template
fn <- "input.dir/Reporting_template_EMPTY.xlsx"
wb <- loadWorkbook(fn)
sheets <- getSheets(wb)
#custom function to write in excel
DataToTemplate <- function(sheet.nm, start.row, start.col, m.out, sheets){
# get cell block from template
sheet <- sheets[[which(names(sheets) == sheet.nm)]]
cb <- CellBlock(sheet, startRow=start.row, startColumn=start.col, noRows=nrow(m.out),
noColumns=ncol(m.out), create=FALSE)
# set needed data into excel
CB.setMatrixData(cellBlock = cb, x = m.out, startRow = 1, startColumn = 1, showNA = FALSE,
cellStyle = NULL)
}
sheet.nm <- "1.0"
out <- as.matrix(dd[which(dd[, "field_nm"] == "a1_0"), "value"])
DataToTemplate(sheet.nm, 5, 3, out, sheets)
fn <- "out.dir/Report2022.xlsx"
saveWorkbook(wb, fn)
最初我使用的是 R 中的“xlsx”库。此外,尝试使用“openxlsx”重写代码并使用 data.frame 而不是矩阵 - 同样的问题。Excel 2016 版本位于保存文件的服务器上。
答: 暂无答案
评论
CB.setMatrixData