Officer使用总结

预备工作

officer包安装,不用之前安装ReporteRs包之前安装那么复杂,直接安装

install.packages("officer")# R4.1.1可以

参考教程

1. https://zhuanlan.zhihu.com/p/340406820
2. https://zhuanlan.zhihu.com/p/111027036
3. https://blog.csdn.net/ToyPython/article/details/90780595
4. https://ardata-fr.github.io/officeverse/officer-for-word.html#add-contents
5. https://davidgohel.github.io/officer/reference/fp_text.html
6. https://www.r-bloggers.com/2020/02/creating-ms-word-reports-using-the-officer-package/
7. https://mran.microsoft.com/snapshot/2018-06-09/web/packages/officer/vignettes/word.html

使用案例

example1

library(officer)
library(magrittr)
library(dplyr)
setwd("/Users/xiaokangyu/Desktop/项目测试")
## 案例1
doc_table=read_docx() %>%
  body_add_par(value = "Hello World!", style = "Normal") %>%
  # body_add_break() %>%  添加一个空白页
  # body_add_par(" ")%>%  # 添加一个空行
  body_add_par(value = "Salut Bretons!", style = "centered") %>%
  print(target = "example1.docx")

在这里插入图片描述

example2

# 案例1
doc_table=read_docx() %>%
  body_add_par(value = "officer是一个生成(处理)Word(docx)和PowerPoint(pptx)的R包。与ReportRs包相比速度要更快,依赖包也更少(ReportRs已经停止维护),常结合flextable包(生成表格),mschart包(生成office图表),rvg(结合ggplot2生成动态图表", style = "Normal") %>%
  # body_add_break() %>%  添加一个空白页
  body_add_par(value = "Salut Bretons!", style = "centered") %>%
  print(target = "example1.docx")

在这里插入图片描述

example3

## 案例2
library(officer)
library(magrittr)

doc2 <- read_docx()
doc2 <- doc2 %>%
  body_add_par("doc2_aaa", style = "Normal") %>%
  body_add_par("doc2_bbb", style = "Normal") %>%
  body_add_par("doc2_ccc", style = "Normal") %>% print(target = "doc2.docx")

doc1 <- read_docx()
doc1 <- doc1 %>%
  body_add_par("doc1_aaa", style = "Normal") %>%
  body_add_par("doc1_bbb", style = "Normal") %>%
  body_add_par("doc1_ccc", style = "Normal") %>%
  body_add_docx(src = "doc2.docx") %>%
  print(target = "Final-Output.docx") 

Final-output的结果是doc2.docx的内容加上doc1写的内容,结果如下
在这里插入图片描述

example 4

library(officer)
library(magrittr) # Package `magrittr` makes officer usage easier.
library(ggplot2)

my_doc <- read_docx()  #初始化一个docx , 里面不填路径使用默认模板
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")

结果如下
在这里插入图片描述

example5

library(ggplot2)
library(flextable)

gg <- ggplot(data = iris, aes(Sepal.Length, Petal.Length)) +
  geom_point()

ft <- flextable(head(iris, n = 10))
ft <- set_table_properties(ft, layout = "autofit")# 设置表的属性

read_docx() %>%
  body_add_par(value = "dataset iris", style = "heading 2") %>%
  body_add_flextable(value = ft ) %>%

  body_add_break() %>%

  body_add_par(value = "plot examples", style = "heading 2") %>%
  body_add_gg(value = gg, style = "centered") %>%

  print(target = "example_break.docx")

example6

rm(list=ls())
library(officer)
library(magrittr)
# 设置字体
f=fp_text(color="red",font.size=10,font.family="宋体")
ft=ftext("我是测试数据集",prop=f)
fp=fpar(ft)

doc=read_docx()%>%body_add_fpar(fp)
print(doc,target="自定义字体.docx")

在这里插入图片描述

example7

library(officer)
library(magrittr)
library(dplyr)
library(flextable)
setwd("/Users/xiaokangyu/Desktop/项目测试")

# create new word document
new.word.doc=function(){
  my.doc=read_docx()
  return(my.doc)
}

# add an empty line
add.empty.line=function(doc){
  body_add_par(doc, " ")
  return("empty line added")
}

#add page break
add.page.break=function(doc){
  body_add_break(doc, pos="after")
  return("page break added")
}

# start landscape
start.landscape=function(doc){
  doc=body_end_section_continuous(doc)
  return("landscape orientation started")
}

# end landscape
end.landscape=function(doc){
  doc=body_end_section_landscape(doc)
  return("landscape orientation ended")
}

# add a title
add.title=function(doc, my.title){
  my.prop=fp_text(font.size = 14, bold = TRUE, font.family = "Times")
  the.title=fpar(ftext(my.title, prop=my.prop))
  body_add_fpar(doc, the.title)
  body_add_par(doc, " ")
  return("title added")
}

# add an image, such as a jpg or png file
add.image=function(doc, image, h=5, w=5){
  body_add_img(doc, src=image,
               height=h, width=w,
               style="centered")
  return("image added")
}

# add a data frame as a table
add.table=function(doc, tbl, col.keys=NULL, col.digits=NULL){
  # create basic flextable
  f.table=qflextable(tbl)
  
  # set numbers of decimals for numeric variables, if specified
  if(!is.null(col.keys)){
    for(j in 1:length(col.keys)){
      f.table=colformat_num(x=f.table,
                            col_keys=col.keys[j],
                            digits=col.digits[j])
    }
  }
  
  # set table borders
  f.table=border_outer(f.table, part="all",
                       border=fp_border(color="black", width = 1))
  f.table=border_inner_h(f.table, part="all",
                         border=fp_border(color="black", width = 1))
  f.table=border_inner_v(f.table, part="all",
                         border=fp_border(color="black", width = 1))
  
  # set fonts
  f.table=font(f.table,  fontname = "Times", part = "all")
  # also set the table's header font as bold
  f.table=bold(f.table, part = "header")
  
  # add the table to the document
  flextable::body_add_flextable(doc, 
                                value = f.table, 
                                align = "left" )
  return("table added")
}

# create an histogram and save it as a png file:
png(filename="histogram.png", width = 6, height = 6, units = 'in', res = 300)
hist(mtcars$wt)
dev.off()
# create a data frame that will become a table in my report
wide.table=mtcars[1:6, ]
wide.table$car=rownames(wide.table)
wide.table=wide.table[, c(12, 1:11)]
narrow.table=wide.table[, 1:4]
# create a new document object
doc=new.word.doc()
# add the report title and an empty line
add.title(doc, "My report")
add.empty.line(doc)
add.title(doc, "narrow table")
add.table(doc, narrow.table, col.keys=c("mpg", "disp"), col.digits=c(1,0))
add.page.break(doc)
# add the histogram with an apropriate title
add.title(doc, "Histogram - portrait")
add.image(doc, "histogram.png", h=3, w=3)
# set the orientation to lndscape
start.landscape(doc)
add.title(doc, "narrow table - landscape")
add.table(doc, narrow.table, col.keys=c("mpg", "disp"), col.digits=c(1,0))
add.empty.line(doc)
# add the wide table in landsacape page orientation
add.title(doc, "wide table in landscape orientation")
add.table(doc, wide.table, col.keys=c("mpg", "disp"), col.digits=c(1,0))
#set the orientation back to portrait
end.landscape(doc)
add.title(doc, "narrow table")
add.table(doc, narrow.table, col.keys=c("mpg", "disp"), col.digits=c(1,0))
# generate the Word document using the print function
print(doc, target="My report.docx")

在这里插入图片描述

注意

officer中默认是没有heading 4的,默认的标题形式只有heading 1,heading 2,heading 3的

如果想使用heading 4, 必须使用模版

library(officer)
library(magrittr)

doc_2 <- read_docx(path = "./template_demo.docx") %>%
  body_add_par("Hello world!", style = "heading 1") %>%
  body_add_par("Hello world!", style = "heading 2") %>%
  body_add_par("Hello world!", style = "heading 3") %>%
  body_add_par("Hello world!", style = "heading 4") %>%
  body_add_par("Hello world!", style = "heading 5") %>%
  body_add_par("dafdafdsf!")

print(styles_info(doc_2)) #显示信息
print(doc_2, target = "example_2.docx")

结果如下
在这里插入图片描述
在这里插入图片描述

example 8

修改表格样式

rm(list=ls())
setwd("/Users/xiaokangyu/Desktop/项目测试/")
suppressPackageStartupMessages(library(tidyverse))
suppressPackageStartupMessages(library(lubridate))
suppressPackageStartupMessages(library(MatchIt))
suppressPackageStartupMessages(library(twang))
suppressPackageStartupMessages(library(table1))
suppressPackageStartupMessages(library(officer))
suppressPackageStartupMessages(library(flextable))



## 我现在某一列进行统计
#4 频数表 按频数大小排序
gen_table1<-function(x){
  dat<-plyr::count(x)
  dat <- dat[order(-dat[,2]),] ####
  total<-length(x)
  percent<-round(dat[,2]/total*100, 2)
  dat1 <- as.matrix(cbind(dat,percent))
  dat1 <- rbind(c("合计", total, 100), dat1)
  colnames(dat1)<-c('变量',"频数","构成比(%)")
  dat1[which(is.na(dat1)), 1] <- "缺失"
  van_table<-data.frame(dat1)
  return(van_table)
}

gen_table2<-function(x){
  dat<-plyr::count(x)
  dat <- dat[order(-dat[,2]),] ####
  total<-length(x)
  percent<-round(dat[,2]/total*100, 2)
  dat1 <- as.matrix(cbind(dat,percent))
  dat1 <- rbind(c("合计", total, 100), dat1)
  colnames(dat1)<-c('变量',"频数","构成比(%)")
  dat1[which(is.na(dat1)), 1] <- "缺失"
  van_table=data.frame(dat1)
  van_table<-van_table%>%flextable()%>%
  theme_booktabs() %>% 
        autofit() %>%
        fix_border_issues()
  return(van_table)
}

aa=gen_table1(mtcars$cyl)
bb=gen_table2(mtcars$cyl)
doc <- read_docx() 
doc=body_add_table(doc,value=aa,style="table_template")
doc=body_add_flextable(doc,value=bb)
print(doc,target="测试表格.docx")
# 可以看到这个字体还是有问题。

结果如下
在这里插入图片描述

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值