Repository navigation
Integrations zh TW
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