有条件地格式化以文本形式存储的openxlsx数字

时间:2020-09-28 20:30:07

标签: r openxlsx

我正在尝试使用openxlsx在xlsx输出中格式化混合类向量。

代码会生成所需的excel文件,但是数字值存储为测试,我该如何有条件地格式化数字?


wb <- openxlsx::createWorkbook() # create workbook

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

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

# convert square brackets to superscript in xlsx output
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 additioanl 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]])
}

# write excel file
openxlsx::saveWorkbook(wb, file="test.xlsx", 
                       overwrite = TRUE)

输出的错误三角形显示“数字存储为文本”。

我尝试添加,但是没有运气。

  openxlsx::writeData(wb, sheet = 'data', names(df)[i], startCol = i, startRow = 1)
  icol <- df[[i]]
  for(j in seq_along(icol)){
    x <- icol[[j]]
    openxlsx::writeData(wb, sheet = 'data', x, startCol = i, startRow = j + 1)
  }
}

excel output

0 个答案:

没有答案
相关问题