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

使用R中的openxlsx包格式化数字,r,openxlsx,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)

我正在尝试使用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)

openxlsx::添加工作表(wb,sheetName='data')#添加工作表
openxlsx::writeData(wb,sheet='data',
x=df,xy=c(1,1),带filter=T)#在工作簿上写入数据
#使质量代码上标
对于(我在grep中(“\\\\\[([A-z0-9\\s]*)\\]”,wb$sharedStrings)){
#如果上标符号中的字符串为空,则只需删除上标符号即可
如果(grepl(“\\\\[\\]”,wb$sharedStrings[[i]])){
wb$sharedStrings[[i]]