r - 从 R 到 Excel 表的上标?

标签 r excel export-to-excel

several great R packages for reading and writing MS Excel spreadsheets 。从 R is easy to LaTeX tables 导出上标(另请参阅 this ),但是有没有办法直接将上标从 R 导出到 Excel 表?

一个例子:

library(openxlsx)
dt <- data.frame(a = 1:3, b = c("a", "b", ""))
dt$try1 <- paste0(dt$a, "^{", dt$b, "}") ## Base R, openxlsx does not seem to know how to handle expression()  
dt$try2 <- paste0(dt$a, "\\textsuperscript{", dt$b, "}") # Should work in xtable
dt$try3 <- paste0("\\textsuperscript{", dt$b, "}") # This does not work either

write.xlsx(dt, "Superscript test.xlsx") 

该代码生成了一个漂亮的 Excel 表格,但不处理 LaTeX 代码(可以理解,因为我们正在导出到 Excel)。也许Excel有一个上标代码可以绕过这个问题?

最佳答案

这个问题已经存在了一段时间,我想OP已经找到了解决方案。无论如何,我的解决方案完全基于this open git issue

为此,您需要定义一个上标表示法并创建一个单独的列,就像您在 dt1$try1 中所做的那样。在我的示例中,我将上标字符括在 _[] 中。只是尽量避免在工作簿的其他情况下可能出现的不明确的符号。

dt <- data.frame(a = 1:3, b = c("a", "b", ""))

dt$sup <- paste0(dt$a, "_[", dt$b, "]") # create superscript col, enclosed in '_[]'

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

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

openxlsx::writeData(wb, sheet=1, x=dt, xy=c(1, 1)) # write data on workbook

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 formating 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::saveWorkbook(wb, file="test.xlsx", overwrite = TRUE)

wb$sharedStrings 包含工作簿单元格中字符串的唯一实例。所选模式捕获 _[] 中包含的单词、数字和空格(或空字符串)的任何实例。循环的第一部分检查上标符号中是否缺少字符,如果 TRUE 则删除该符号。

关于r - 从 R 到 Excel 表的上标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40234742/

相关文章:

r - 如何将 data.frame 列从 Factor 转换为数字

r - 通过 Shiny 中的串扰将 Plotly 与 DT 结合使用

r - 使用可变偏移量分割字符串

java - 如何使用 java Apache POI 在 excel 中动态构建边框

excel - 当用户在 MS Access VBA 中的参数请求输入框中点击取消时如何获取返回值?

ms-access - 将数据从连续表单导出到 Excel(不带标题字段)

asp.net - C# : Datagrid to Excel . 创建的 Excel 文件中缺少单元格边框

c# - 在 C# 中,使用 Spire.Xls,在折叠行上方使用折叠/展开选项对 excel 工作表行进行分组

r - 将R数据作为csv直接写入s3

vba - 从 VBA 组合框中删除重复项