You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Shiny App中渲染带格式的Word文档内容,替代手动HTML编码?

解决Shiny App导入Word格式文本的简便方法

方案1:Word转Markdown后渲染

先把带格式的Word文档转成Markdown(可用Word自带导出功能、VS Code插件或在线工具完成),再在Shiny中直接渲染Markdown内容,无需手动编写HTML标签。

示例代码:

library(shiny)
library(markdown)

ui <- fluidPage(
  uiOutput("coxModel")
)

server <- function(input, output) {
  # 读取本地Markdown文件内容,也可直接传入Markdown格式字符串
  md_content <- readLines("你的文档.md", warn = FALSE) |> paste(collapse = "\n")
  
  output$coxModel <- renderUI(
    tags$div(
      style = "text-align:justify",
      HTML(markdown::renderMarkdown(text = md_content))
    )
  )
}

shinyApp(ui, server)

Markdown的加粗、斜体、代码块等格式会自动转为对应HTML,比手动写标签效率高很多。

方案2:用officer直接读取Word文档

无需转格式,用officer包读取Word内容并转为可渲染的格式:

示例代码:

library(shiny)
library(officer)
library(rmarkdown)

ui <- fluidPage(
  uiOutput("coxModel")
)

server <- function(input, output) {
  # 读取Word文档
  doc <- read_docx("你的文档.docx")
  # 提取带格式的内容并转为Markdown
  md_content <- docx_summary(doc)$content |> paste(collapse = "\n")
  
  output$coxModel <- renderUI(
    tags$div(
      style = "text-align:justify",
      HTML(rmarkdown::renderMarkdown(text = md_content))
    )
  )
}

shinyApp(ui, server)

适合需要频繁更新Word文档、不想手动转格式的场景。

方案3:静态内容直接用includeMarkdown引入

如果文本内容不需要动态生成,可直接在UI中引入Markdown文件,无需renderUI:

library(shiny)

ui <- fluidPage(
  div(
    style = "text-align:justify",
    includeMarkdown("你的文档.md")
  )
)

server <- function(input, output) {}

shinyApp(ui, server)

这种方式更简洁,性能也更优。


内容的提问来源于stack exchange,提问作者Village.Idyot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 12:35:10