Skip to content

Integrations ja

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

Rails、Rack、バックグラウンドジョブで docxi を使う

docxi にはプラグインや組み込みの連携機能はありません。StringIO を返すただの Ruby なので、文字列を送信または保存できる場所ならどこでも使えます。このページでは一般的なつなぎ方を紹介します。Rails のコントローラーの例は README と同じもので、テストスイートは Rails 5.2 から 8.1 を読み込んだ状態で実行しています。

Rails のコントローラー:ファイルをブラウザーに送信する

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
end

send_data は Content-Disposition: attachment を設定するため、ブラウザーはファイルをダウンロードします。Bundler を使っている場合、docxi は Gemfile から自動で読み込まれます。

Rails のバックグラウンドジョブ:リクエストの外でファイルを作る

大きなドキュメントや、遅いクエリから作るドキュメントは、ジョブで生成するのが適しています。

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 とその他のフレームワーク

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)

関連ページ


← Wiki ホーム · README

Clone this wiki locally