Repository navigation
Integrations zh CN
Hammad Maqbool edited this page Oct 29, 2026
·
1 revision
English · 简体中文 · 繁體中文 · Español · العربية · Français · Português (Brasil) · Deutsch · हिन्दी · 日本語 · 한국어 · Русский · Bahasa Indonesia · Türkçe · Italiano · Tiếng Việt
docxi 没有插件,也没有内置的集成。它就是返回 StringIO 的普通 Ruby 代码,所以任何能发送或保存字符串的地方都能使用它。本页展示常见的接入方式。Rails 控制器的写法与 README 中的示例相同,测试套件会在加载 Rails 5.2 到 8.1 的情况下运行。
class ReportsController < ApplicationController
def show
word = Docxi::Document.new
word.document.p { |p| p.text "Report for #{Date.today}" }
send_data word.render.string,
filename: "report.docx",
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
end
endsend_data 会设置 Content-Disposition: attachment,因此浏览器会下载该文件。使用 Bundler 时,docxi 会从 Gemfile 自动加载。
大型文档,或者依赖慢查询生成的文档,最好放在后台任务中生成:
class MonthlyReportJob < ApplicationJob
queue_as :default
def perform(path)
word = Docxi::Document.new
word.document.p { |p| p.text "Monthly report", bold: true, size: 16 }
File.binwrite(path, word.render.string)
end
end该任务把文件写到你指定的路径。文件接下来的去向(例如存储或邮件)由你的应用决定。
任何 Rack 应用都可以直接返回字节内容:
require "docxi"
class ReportApp
def call(env)
word = Docxi::Document.new
word.document.p { |p| p.text "Generated by a Rack app" }
headers = {
"content-type" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"content-disposition" => 'attachment; filename="report.docx"'
}
[200, headers, [word.render.string]]
end
end在 config.ru 中用 run ReportApp.new 挂载它。同样的方法也适用于 Sinatra、Hanami,以及任何能把字符串作为响应体发送的框架。
docxi 不需要服务器,也不需要办公软件,所以普通的 Ruby 脚本就能使用它:
require "docxi"
word = Docxi::Document.new
word.document.p { |p| p.text "Nightly export" }
File.binwrite(ARGV.fetch(0, "export.docx"), word.render.string)docxi wiki · README · Installation · Troubleshooting · Report an issue · MIT License
Start
Build documents
Help
Project
Links
Languages