Repository navigation
Getting Started 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
このガイドでは、空のフォルダーから書式付きの .docx ファイルを作るまでを説明します。Ruby の基本を知っていることを前提としています。Rails や Microsoft Word は必要ありません。
gem install docxiGemfile のあるプロジェクトでは、代わりに gem "docxi", "~> 0.1" を追加して bundle install を実行します。詳しくはインストールを参照してください。
次の内容を hello.rb として保存します。
require "docxi"
word = Docxi::Document.new
document = word.document
document.p(align: "center") do |p|
p.text "Hello, Word", size: 24, bold: true
end
File.binwrite("hello.docx", word.render.string)ruby hello.rb(Bundler を使うプロジェクトでは bundle exec ruby hello.rb)を実行し、hello.docx を開きます。
-
Docxi::Document.newは、デフォルトの余白を持つ空のドキュメントを作成します。 -
word.documentはドキュメントの本文です。追加するものはすべてここを通ります。 -
document.pは段落を追加します。align:などpに渡したオプションは、段落とその中のテキストに適用されます。 -
p.textはテキストのラン(run)を追加します。size:の単位はポイントです。 -
word.renderは.docxパッケージを組み立ててStringIOを返します。その.stringにファイルのバイト列が入っています。
require "docxi"
word = Docxi::Document.new
document = word.document
document.p { |p| p.text "Quarterly summary", size: 16, bold: true }
document.p do |p|
p.text "Revenue grew ", space: true
p.text "12%", bold: true, color: "007A33"
p.text " compared with last quarter.", space: true
end
document.p(ul: true) { |p| p.text "New customers: 48" }
document.p(ul: true) { |p| p.text "Customers lost: 3" }
document.table(columns_width: [200, 100]) do |table|
table.tr(fill: "D9D9D9", bold: true) do |tr|
tr.tc { |tc| tc.text "Region" }
tr.tc { |tc| tc.text "Sales" }
end
table.tr do |tr|
tr.tc { |tc| tc.text "North" }
tr.tc { |tc| tc.text "$41,000", align: "right" }
end
end
File.binwrite("summary.docx", word.render.string)注意点が 2 つあります。
-
space: trueは、ランの先頭や末尾の空白を保持します。指定しないと Word が空白を削除し、単語がつながってしまいます。 -
trのオプションはその行のすべてのセルに適用されるため、見出し行全体が網かけと太字になります。
- 使用例:レポート、請求書、手紙の完全なレシピ
- 機能:段落、テキスト、表、画像、ヘッダーとフッターのすべてのオプション
- 連携:Rails のコントローラーからドキュメントを送信する
- ベストプラクティス:よくある落とし穴を事前に避ける
docxi wiki · README · Installation · Troubleshooting · Report an issue · MIT License
Start
Build documents
Help
Project
Links
Languages