How do I maintain the formatting of text in a cell in an Excel spreadsheet when importing into R markdown?

时间:2017-11-13 06:25:05

标签: r excel r-markdown kableextra kable

I have an .xlsx file in which some of the cells have boldface numbers and some have italicized numbers. I am using read_xlsx to read the .xlsx file into R and then using kable to present it with this code:

knitr::kable(spreadsheet, format="latex", booktabs = T) %>% 
kable_styling(latex_options = c("striped"))

I cannot get the boldface and italics numbers from the .xlsx to stay boldface and italicized when they appear in the .pdf generated from the .Rmd file. How do I do this?

1 个答案:

答案 0 :(得分:1)

在回答您的问题时,您无法维护格式化,但您可以复制它。

运行read_xlsx()函数时,它会从单元格中提取数据,但不保留任何格式。因此,任何粗体字体都不会自动传输到R。

实现所需内容的最简单方法是在将数据加载到R后添加粗体文本。kableExtra非常适合执行此类操作。以下是一个示例,使用column_specrow_spec函数更改单元格的格式:

```{r}
library(kableExtra)

knitr::kable(iris[1:5,], format = "latex", booktab = TRUE) %>%
  column_spec(1, bold = T) %>%
  row_spec(0, bold = T, color = "red")

```

enter image description here

您可以自定义许多属性(运行?row_spec以加载帮助程序):

  • 字体大小
  • 对齐
  • 文字角度
  • 文字颜色
  • 背景颜色

如果您需要更精细地调整特定单元格的单元格格式,您可以调查cell_spec函数。

  

在此处查看自定义LaTeX表的完整指南:https://haozhu233.github.io/kableExtra/awesome_table_in_pdf.pdf