如何使用R的officer包删除docx文档开头的空白行?
解决officer生成Word文档开头空白行的问题
我之前也碰到过这个一模一样的问题!officer包初始化docx文档时,会自动创建一个默认的空段落——这就是你看到开头空白的根源,哪怕启用cursor_begin()也没法直接消除它,得手动处理这个默认段落才行。
给你两个实用的解决办法:
方法1:先移除默认空段落(推荐)
直接在添加内容前用body_remove()删掉那个自动生成的空段落,代码如下:
library(officer) library(magrittr) my_docx <- read_docx() %>% body_remove() %>% # 移除初始化时的默认空段落 body_add_par("Hello here is a test sentence to see if there is a blank line above it.", style = "Normal") %>% print(target = "test.docx")
方法2:通过光标位置插入到默认段落前
如果你不想删除默认段落,也可以用pos = "before"参数把内容插在默认空段落的前面,这样开头就会显示你的文本而非空白:
library(officer) library(magrittr) my_docx <- read_docx() %>% cursor_begin() %>% body_add_par("Hello here is a test sentence to see if there is a blank line above it.", style = "Normal", pos = "before") %>% print(target = "test.docx")
两种方法都能解决开头空白的问题,个人更推荐第一种,逻辑更清晰,也不会留下多余的空段落。
内容的提问来源于stack exchange,提问作者Prevost
相关产品推荐
相关产品推荐

