Repository navigation
Getting Started zh TW
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 docxi如果專案使用 Gemfile,請改為加入 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加入一個段落。傳給p的選項(例如align:)同時作用於段落及其中的文字。 -
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)有兩點需要注意:
-
space: true會保留文字片段開頭或結尾的空格。如果不加,Word 會捨棄這個空格,前後的字就會黏在一起。 -
tr上的選項會套用到該列的每個儲存格,所以整個標題列都有網底並以粗體顯示。
docxi wiki · README · Installation · Troubleshooting · Report an issue · MIT License
Start
Build documents
Help
Project
Links
Languages