officer是一個(gè)生成(處理)Word(docx)和PowerPoint(pptx)的R包。與ReportRs包相比速度要更快,依賴(lài)包也更少(好像也是這個(gè)作者寫(xiě)的,但是ReportRs要依賴(lài)于rjava,不便維護(hù)),常結(jié)合flextable包(生成表格),mschart包(生成office圖表),rvg(結(jié)合ggplot2生成動(dòng)態(tài)圖表)。
word文檔主要函數(shù)分類(lèi)
1.添加內(nèi)容作為段落:圖像,表格,文字。使用body_add_*功能
- body_add_par 添加段落
- body_add_img 添加圖片
- body_add_table 表格
- body_add_break 換行
- body_add_toc 目錄
- body_add_gg ggplot圖片
2.在現(xiàn)有段落內(nèi)添加文字或圖像。內(nèi)容被添加到光標(biāo)所在的段落中,使用slip_in_*功能: - slip_in_img()
- slip_in_seqfield()
-
slip_in_text()
3.移動(dòng)光標(biāo) - cursor_begin()
- cursor_end()
- cursor_reach()
- cursor_backward()
- cursor_forward()
-
cursor_bookmark()
4.刪除內(nèi)容 - body_remove()
5.搜索和替換 - body_replace_text_at_bkm()
- body_replace_all_text()
示例
library(officer)
library(magrittr) # Package `magrittr` makes officer usage easier.
library(ggplot2)
my_doc <- read_docx() #初始化一個(gè)docx , 里面不填路徑使用默認(rèn)模板
styles_info(my_doc) #顯示信息
gg <- ggplot(data = iris, aes(Sepal.Length, Petal.Length)) +
geom_point()
my_doc %>% #可以使用magrittr方式一步步添加
body_add_par(value = "Table of content", style = "heading 1") %>%
body_add_toc(level = 2) %>%
body_add_break() %>%
body_add_par(value = "dataset iris", style = "heading 2") %>%
body_add_table(value = head(iris), style = "table_template" ) %>%
body_add_par(value = "plot examples", style = "heading 1") %>%
body_add_gg(value = gg, style = "centered" ) %>%
print(target = "body_add_demo.docx")

輸出結(jié)果
相關(guān)網(wǎng)站
- officer 生成 docx pptx
- https://davidgohel.github.io/officer/
- https://github.com/davidgohel/officer
- flextable 處理表格
- https://davidgohel.github.io/flextable/
- https://github.com/davidgohel/flextable