Repository navigation
Getting Started 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
本指南带你从一个空文件夹开始,生成一个带格式的 .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