数据框到字表?

 书友14395217 发布于 2022-12-26 12:40

有没有办法通过rmarkdown轻松将数据框转换为Word表格?

如果我在RStudio中使用rmarkdown创建一个Word文档,我会得到一个很好的打印表,但它不会被识别为Word表.它可以完成吗?

   ```{r}
   name_of_df
   ```

Victorp.. 19

编辑: ReporteRs仍然保持,但不会再发展.使用官员和flextable代替:

library(officer)
library(flextable)
library(magrittr)

# Create flextable object
ft <- flextable(data = mtcars) %>% 
  theme_zebra %>% 
  autofit
# See flextable in RStudio viewer
ft

# Create a temp file
tmp <- tempfile(fileext = ".docx")

# Create a docx file
read_docx() %>% 
  body_add_flextable(ft) %>% 
  print(target = tmp)

# open word document
browseURL(tmp)

结束编辑

您好,您也可以尝试ReporteRs将data.frame转换为Word表格,执行此操作的功能是FlexTable:

library(ReporteRs)
library(magrittr)

docx( ) %>% 
  addFlexTable( mtcars %>%
                  FlexTable( header.cell.props = cellProperties( background.color =  "#003366" ),
                             header.text.props = textBold( color = "white" ),
                             add.rownames = TRUE ) %>%
                  setZebraStyle( odd = "#DDDDDD", even = "#FFFFFF" ) ) %>%
  writeDoc( file = "exemple.docx" )

# open the Word document
browseURL("exemple.docx")

在此输入图像描述

使用markdown,我认为这只适用于HTML:

---
title: "HTML table"
output: html_document
---

```{r, results='asis'}
library(ReporteRs)
tabl = FlexTable( mtcars,
                  header.cell.props = cellProperties( background.color = "#003366" ),
                  header.text.props = textBold( color = "white" ),
                  add.rownames = TRUE )
tabl = setZebraStyle( tabl, odd = "#DDDDDD", even = "#FFFFFF" )
cat(as.html(tabl))
```

这是另一个关于如何使用ReporteRs创建word文档的示例:

library(ReporteRs)
# Create a docx object
doc = docx()
# add a document title
doc = addParagraph( doc, "A FlexTable example", stylename = "TitleDoc" )
# add a section title
doc = addTitle( doc, "How to turn a data.frame into a Word table", level = 1 )
# some text
doc = addParagraph( doc, "We use the mtcars dataset as example.", stylename = "DocDefaults" )
# add a table
MyFTable = FlexTable( data = mtcars[1:10, ], add.rownames = TRUE )
# format body content
MyFTable[3:4, "cyl"] = cellProperties( background.color = "red" )
MyFTable["Valiant", ] = cellProperties( background.color = "blue" )
doc = addFlexTable(doc, MyFTable)
# write the doc
writeDoc( doc, file = "exemple.docx" )
# open the Word doc
browseURL("exemple.docx")

在此输入图像描述

有关更多示例,请访问http://davidgohel.github.io/ReporteRs/word.html

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有