使用 R 中的 openxlsx 包格式化数字

jku*_*kud 5 r openxlsx

我正在尝试使用 openxlsx 格式化某些列,以将 r 数据帧写入 Excel 文件。

这是 R 数据框的片段:

在此输入图像描述

“种子”列中的方括号部分用于为 Excel 输出添加上标。

这是我用来编写该文件的代码:


openxlsx::addWorksheet(wb, sheetName = 'data') # add sheet

openxlsx::writeData(wb, sheet ='data', 
                    x=df, xy=c(1, 1),withFilter = T) # write data on workbook

# make quality codes superscript
for(i in grep("\\_\\[([A-z0-9\\s]*)\\]", wb$sharedStrings)){
  # if empty string in superscript notation, then just remove the superscript notation
  if(grepl("\\_\\[\\]", wb$sharedStrings[[i]])){
    wb$sharedStrings[[i]] <- gsub("\\_\\[\\]", "", wb$sharedStrings[[i]])
    next # skip to next iteration
  }
  
  # insert additional formatting in shared string
  wb$sharedStrings[[i]] <- gsub("<si>", "<si><r>", gsub("</si>", "</r></si>", wb$sharedStrings[[i]]))
  
  # find the "_[...]" pattern, remove brackets and udnerline and enclose the text with superscript format
  wb$sharedStrings[[i]] <- gsub("\\_\\[([A-z0-9\\s]*)\\]",
                                "</t></r><r><rPr><vertAlign val=\"superscript\"/></rPr><t xml:space=\"preserve\">\\1</t></r><r><t xml:space=\"preserve\">",
                                wb$sharedStrings[[i]])
}

openxlsx::modifyBaseFont(wb, fontSize = 10, fontName = 'Arial')

# right-justify data
openxlsx::addStyle(wb, sheet = 'data', 
         style = openxlsx::createStyle(halign = "right"), rows = 1:nrow(df)+1, cols = 3:12, gridExpand = TRUE)

#apply to rows with "All" in column B
openxlsx::conditionalFormatting(wb,sheet = 'data',
                      cols = 1:ncol(df), 
                      rows = 1:nrow(df)+1,
                      rule = 'LEFT($B2,3)="ALL"',
                      style = openxlsx::createStyle(textDecoration = 'bold', bgFill = '#dad9d9'))

# format numbers
openxlsx::addStyle(wb = wb, sheet = 'data', 
                   style = openxlsx::createStyle(numFmt = "#,###.0"), 
                   rows = 1:nrow(df)+1, cols = c(5:7,10:12),gridExpand = T)

# write excel file
openxlsx::saveWorkbook(wb, file="file.xlsx", 
                       overwrite = TRUE)
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

在此输入图像描述

我试图有条件地将 seed/harv/yield/prod 列中的数字格式化为数字,但“F”值最多只能创建一个混合类向量。(我需要这些F!)

有任何想法吗?

谢谢!