
文档打印 是桌面应用、后台服务以及服务器端系统中非常常见的需求。在实际开发和业务场景中,开发者往往需要在无用户交互的情况下完成打印操作,例如:静默打印文件、将打印任务发送到指定打印机,或通过代码精细控制打印行为。
本文将介绍如何使用 Spire.Printing,在 Windows、Linux 和 macOS 平台上,通过 C# 实现 PDF 与 Office 文档的自动化打印。你将了解如何构建可打印的文档流、以代码方式选择打印机,并配置高级打印参数,从而在现代 .NET 应用中实现稳定、可控的跨平台打印方案。
目录
Spire.Printing 以 NuGet 包的形式发布,可通过标准方式添加到项目中:
Install-Package Spire.Printing
Spire.Printing 是一款面向现代 .NET 应用的 跨平台打印库。当与支持 .NET Standard 的 Spire.Office 系列组件配合使用时,可在 无需依赖 Microsoft Office Interop 的情况下,在 Windows、Linux 和 macOS 上打印 Word、Excel、PowerPoint、PDF 等文档。
目前支持的 .NET 运行时包括:
支持的平台环境包括:
Spire.Printing 的核心设计思想是:将“可直接打印的文档流”发送到打印机。在不同操作系统下,可打印流的格式略有不同:Windows 下使用 XPS 文档流;Linux / macOS 下通常使用 PDF 文档流。
在实际项目中,Spire.Printing 通常与 Spire.Office for .NETStandard 配合使用,形成统一的跨平台打印流程。
整体步骤如下:
using Spire.Printing;
IPrintDocumentStream documentStream;
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
System.Runtime.InteropServices.OSPlatform.Windows))
{
// Windows 平台使用 XPS
documentStream = new XpsPrintDocument("test.xps");
}
else
{
// Linux / macOS 使用 PDF
documentStream = new PdfPrintDocument("test.pdf");
}
// 创建 PrintDocument
PrintDocument printDocument = new PrintDocument(documentStream);
// 设置纸张大小
printDocument.PrintSettings.PaperSize = PaperSize.A4;
// 设置打印份数
printDocument.PrintSettings.Copies = 2;
// 选择打印页码范围
printDocument.PrintSettings.SelectPageRange(2, 5);
// 双面打印
if (printDocument.PrintSettings.CanDuplex)
{
printDocument.PrintSettings.Duplex = Duplex.Vertical;
}
// 是否逐份打印
printDocument.PrintSettings.Collate = true;
// 指定打印机(不设置则使用默认打印机)
printDocument.PrintSettings.PrinterName = "Your Printer Name";
// 输出为文件
printDocument.PrintSettings.PrintToFile("toXps.xps");
// 记录打印日志
printDocument.PrintSettings.PrintLogger =
new DefaultPrintLogger("log.txt");
// 执行打印
printDocument.Print();
// 释放资源
printDocument.Dispose();
这种基于“文档流”的设计,使打印流程在不同平台上保持一致,同时所有打印行为都可以通过 PrintSettings API 进行精细控制。
在实际项目中,Spire.Printing 通常与对应的 Spire.Office 文档组件配合使用,包括 Spire.Doc、Spire.XLS、Spire.Presentation、Spire.PDF。这些组件负责加载原始文档,并将其保存为 PDF 或 XPS 的文档流,再交由 Spire.Printing 发送至打印机。

安装库
Install-Package Spire.Printing
Install-Package Spire.Docfor.NETStandard
示例代码
using Spire.Doc;
using Spire.Printing;
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
using (Document document = new Document())
{
document.LoadFromFile("test.docx");
var fileFormat = !isWindows
? Spire.Doc.FileFormat.PDF
: Spire.Doc.FileFormat.XPS;
MemoryStream stream = new MemoryStream();
document.SaveToStream(stream, fileFormat);
IPrintDocumentStream docStream = !isWindows
? new PdfPrintDocument(stream)
: new XpsPrintDocument(stream);
PrintDocument printDoc = new PrintDocument(docStream);
printDoc.PrintSettings.SelectPageRange(1, 1);
printDoc.Print();
printDoc.Dispose();
}
安装库
Install-Package Spire.Printing
Install-Package Spire.XLSfor.NETStandard
示例代码
using Spire.Xls;
using Spire.Printing;
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
using (Workbook workbook = new Workbook())
{
workbook.LoadFromFile("test.xlsx");
var fileFormat = !isWindows
? Spire.Xls.FileFormat.PDF
: Spire.Xls.FileFormat.XPS;
MemoryStream stream = new MemoryStream();
workbook.SaveToStream(stream, fileFormat);
IPrintDocumentStream xlsStream = !isWindows
? new PdfPrintDocument(stream)
: new XpsPrintDocument(stream);
PrintDocument printXls = new PrintDocument(xlsStream);
printXls.PrintSettings.SelectPageRange(1, 1);
printXls.Print();
printXls.Dispose();
}
安装库
Install-Package Spire.Printing
Install-Package Spire.PDFfor.NETStandard
示例代码
using Spire.Pdf;
using Spire.Printing;
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
using (PdfDocument pdfDocument = new PdfDocument())
{
pdfDocument.LoadFromFile("test.pdf");
var fileFormat = !isWindows
? Spire.Pdf.FileFormat.PDF
: Spire.Pdf.FileFormat.XPS;
MemoryStream stream = new MemoryStream();
pdfDocument.SaveToStream(stream, fileFormat);
IPrintDocumentStream pdfStream = !isWindows
? new PdfPrintDocument(stream)
: new XpsPrintDocument(stream);
PrintDocument printPdf = new PrintDocument(pdfStream);
printPdf.PrintSettings.SelectPageRange(1, 1);
printPdf.Print();
printPdf.Dispose();
}
安装库
Install-Package Spire.Printing
Install-Package Spire.Presentationfor.NETStandard
示例代码
using Spire.Presentation;
using Spire.Printing;
bool isWindows = System.Runtime.InteropServices.RuntimeInformation
.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows);
using (Presentation presentation = new Presentation())
{
presentation.LoadFromFile("test.pptx");
var fileFormat = !isWindows
? Spire.Presentation.FileFormat.PDF
: Spire.Presentation.FileFormat.XPS;
MemoryStream stream = new MemoryStream();
presentation.SaveToFile(stream, fileFormat);
IPrintDocumentStream pptStream = !isWindows
? new PdfPrintDocument(stream)
: new XpsPrintDocument(stream);
PrintDocument printPpt = new PrintDocument(pptStream);
printPpt.PrintSettings.SelectPageRange(1, 1);
printPpt.Print();
printPpt.Dispose();
}
在自动化打印或跨平台打印场景中,Spire.Printing 通过 PrintSettings 提供了对打印机、纸张和页面输出的更精细控制,非常适合无人值守服务和批量打印任务。
IEnumerable<string> printers = printDocument.PrintSettings.Printers;
// 根据业务逻辑选择打印机
string selectedPrinter = printers.First();
printDocument.PrintSettings.PrinterName = selectedPrinter;
该方式适用于多打印机环境,或需要明确指定打印目标的场景。
IEnumerable<PaperSize> paperSizes =
printDocument.PrintSettings.PaperSizes;
PaperSize selectedSize = paperSizes.First();
printDocument.PrintSettings.PaperSize = selectedSize;
通过这种方式可确保所选纸张尺寸与目标打印机兼容。
// 连续页码
printDocument.PrintSettings.SelectPageRange(2, 5);
// 指定页码
int[] pages = { 1, 3, 5, 7 };
printDocument.PrintSettings.SelectSomePages(pages);
注意:同一次打印任务中只能使用其中一种方式。
这些高级设置使得打印输出具备高度可控性,特别适合自动化处理、多文档批量打印以及对打印结果一致性要求较高的业务场景。
在未授权的情况下,Spire.Printing 仅允许打印前 10 页内容。 通过为 Spire.Office for .NET 或对应的文档组件(如 Spire.Doc、Spire.XLS、Spire.PDF、Spire.Presentation)配置许可证,可移除该限制。
Spire.Pdf.License.LicenseProvider.SetLicenseKey(key);
Spire.Doc.License.LicenseProvider.SetLicenseKey(key);
Spire.Xls.License.LicenseProvider.SetLicenseKey(key);
Spire.Presentation.License.LicenseProvider.SetLicenseKey(key);
有关许可证配置的详细说明,请参考:授权应用指南。
Spire.Printing 为 C# 应用提供了一套灵活、可靠的专业打印解决方案。它支持在 Windows、Linux 和 macOS 上,以文档流方式打印 PDF、Word、Excel 和 PowerPoint 文件,并可与 Spire.Office for .NET(尤其是 .NET Standard 版本)无缝配合使用。
在掌握基础打印流程后,开发者可以根据实际业务需求,灵活应用 打印机选择、纸张设置、页码控制等高级功能,轻松构建稳定的自动化打印系统。
在评估或短期开发阶段,也可以申请临时许可证,以在开发过程中解除试用限制。
Spire.PDF for Python 12.1.3 现已正式发布。该版本支持自定义签名外观,以及获取文本的字体样式。此外,还修复了一些在处理 PDF 文件时出现的问题。详情请查阅以下内容。
新功能:
class MyPdfCustomAppearance(IPdfSignatureAppearance):
def __init__(self):
pass
def Generate(self, g: PdfCanvas):
x = 0.0
y = 0.0
fontSize = 10.0
font = PdfTrueTypeFont("SimSun", fontSize, PdfFontStyle.Regular, True)
lineHeight = fontSize
image = PdfImage.FromFile(inputImage)
g.DrawImage(image, x, y)
x = float(image.Width)
g.DrawString("Signer: Gary", font, PdfBrushes.get_Red(), PointF(x, y))
y += lineHeight + 5
g.DrawString("Phone: +86 12345678", font, PdfBrushes.get_Black(), PointF(x, y))
y += lineHeight + 5
g.DrawString("Address: Sichuan Province, China", font, PdfBrushes.get_Black(), PointF(x, y))
doc = PdfDocument()
doc.LoadFromFile(inputFile)
signatureMaker = PdfOrdinarySignatureMaker(doc, inputFile_pfx, "e-iceblue")
my_appearance = MyPdfCustomAppearance()
customAppearance = PdfCustomAppearance(my_appearance)
signatureMaker.MakeSignature("Signer", doc.Pages.get_Item(0), 90.0, 550.0, 270.0, 640.0, customAppearance)
doc.SaveToFile(outputFile)
doc.Close()
# 加载PDF文档
doc = PdfDocument()
doc. LoadFromFile(inputFile)
# 定义一个矩形区域
rctg = RectangleF (0.0, 0.0, 200.0, 300.0)
pdfPageBase = doc.Pages.get_Item (0)
finder = PdfTextFinder(pdfPageBase)
finder.Options.Parameter = TextFindParameter.none
finder.Options.Area = rctg
# 查找矩形区域文本
findouts = finder.FindAllText()
sb=[]
for fragment in findouts:
sb.append (fragment.Text)
sb.append (fragment.TextStates[0].FontName)
sb.append(str(round(fragment.TextStates[0].FontSize,2)))
result ="result.txt"
问题修复:
CSV(逗号分隔值)文件凭借其简洁性、易读性以及跨系统兼容性,仍是现代软件开发领域中应用最广泛的数据交换格式之一。无论是数据导出、系统间同步,还是批量数据处理,CSV 都扮演着关键角色。对于 在 C# 中创建 CSV 文件的开发需求,Spire.XLS for .NET 库提供了一套强大且易用的解决方案—无需手动拼接字符串,也无需依赖本地 Excel 环境,通过简洁 API 即可完成各类 CSV 操作。
本文将介绍如何使用 Spire.XLS 通过 C# 生成 CSV 文件,覆盖基础创建、列表映射、Excel 转换三大高频需求,并附完整代码与详细解析。
Spire.XLS for .NET 是一款专注于电子表格处理的专业 API,不仅支持 Excel 全格式操作,对 CSV 文件也提供了深度适配,其核心优势如下:
在开始编码前,需完成以下准备工作:
PM> Install-Package Spire.XLS
适用于需手动定义表头与数据的简单场景,以下示例演示了如何从零构建 CSV 文件:
using System;
using System.Text;
using Spire.Xls;
namespace CreateBasicCSV
{
class Program
{
static void Main(string[] args)
{
// 1. 初始化工作簿(Spire.XLS核心操作对象)
Workbook workbook = new Workbook();
// 2. 创建工作表(CSV文件对应单个工作表)
Worksheet worksheet = workbook.Worksheets.Add("产品数据");
// 3. 定义CSV表头(A1-D1为表头单元格)
worksheet.Range["A1"].Value = "产品编号";
worksheet.Range["B1"].Value = "产品名称";
worksheet.Range["C1"].Value = "售价";
worksheet.Range["D1"].Value = "库存状态";
// 4. 填充示例数据(按行赋值,适配不同数据类型)
worksheet.Range["A2"].Value2 = 1001; // 数值类型
worksheet.Range["B2"].Value = "戴尔XPS 15笔记本"; // 字符串类型
worksheet.Range["C2"].Value2 = 1299.99; // 浮点类型
worksheet.Range["D2"].Value = "有货"; // 字符串类型
worksheet.Range["A3"].Value2 = 1002;
worksheet.Range["B3"].Value = "无线蓝牙鼠标";
worksheet.Range["C3"].Value2 = 29.99;
worksheet.Range["D3"].Value = "无货";
worksheet.Range["A4"].Value2 = 1003;
worksheet.Range["B4"].Value = "机械键盘(青轴)";
worksheet.Range["C4"].Value2 = 89.99;
worksheet.Range["D4"].Value = "有货";
// 5. 导出为CSV文件(指定分隔符为逗号,编码为UTF-8)
worksheet.SaveToFile("基础产品列表.csv", ",", Encoding.UTF8);
workbook.Dispose(); // 释放资源
Console.WriteLine("CSV文件创建成功!");
}
}
}
核心代码解析:
Workbook 对象(Spire.XLS 操作 Excel/CSV 的核心对象)。Value:用于文本/字符串类型数据。Value2:用于布尔值、字符串、数字、日期等类型数据。SaveToFile 方法将工作表转换为 CSV 文件。输出结果:
实际开发中,数据常存储在 List<T> 等集合中,以下示例演示如何将 Product 对象列表直接映射为 CSV 文件,适配结构化数据场景:
using System;
using System.Collections.Generic;
using System.Text;
using Spire.Xls;
namespace CreateCSVFromList
{
// 定义产品实体类(与CSV字段一一对应)
public class Product
{
public int 商品编号 { get; set; }
public string 商品名称 { get; set; }
public decimal 售价 { get; set; }
public bool 是否有货 { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 1. 准备结构化列表数据
List<Product> productList = new List<Product>()
{
new Product { 商品编号 = 1001, 商品名称 = "笔记本电脑", 售价 = 999.99m, 是否有货 = true },
new Product { 商品编号 = 1002, 商品名称 = "纯棉T恤", 售价 = 19.99m, 是否有货 = false },
new Product { 商品编号 = 1003, 商品名称 = "陶瓷咖啡杯", 售价 = 8.99m, 是否有货 = false },
new Product { 商品编号 = 1004, 商品名称 = "静音无线鼠标", 售价 = 24.99m, 是否有货 = true }
};
// 2. 初始化Spire.XLS核心对象
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0]; // 默认使用第一个工作表
// 3. 写入CSV表头(索引从1开始)
worksheet.Range[1, 1].Text = "商品编号"; // 第1行第1列
worksheet.Range[1, 2].Text = "商品名称"; // 第1行第2列
worksheet.Range[1, 3].Text = "售价"; // 第1行第3列
worksheet.Range[1, 4].Text = "是否有货"; // 第1行第4列
// 4. 批量填充列表数据(从第2行开始写入)
for (int i = 0; i < productList.Count; i++)
{
int currentRow = i + 2; // 行号:从2开始(跳过表头)
Product product = productList[i];
// 按数据类型赋值,确保CSV数据格式正确
worksheet.Range[currentRow, 1].NumberValue = product.商品编号; // 数值型
worksheet.Range[currentRow, 2].Text = product.商品名称; // 字符串型
worksheet.Range[currentRow, 3].NumberValue = (double)product.售价; // 十进制转双精度
worksheet.Range[currentRow, 4].Text = product.是否有货 ? "是" : "否"; // 布尔值转中文描述
}
// 5. 保存CSV文件
string outputPath = "结构化产品列表.csv";
worksheet.SaveToFile(outputPath, ",", Encoding.UTF8);
workbook.Dispose();
Console.WriteLine($"CSV文件已保存至:{outputPath}");
}
}
}
核心代码说明:
Workbook 管理工作表。.Text 属性。.NumberValue 属性。.BooleanValue 属性。
将 Excel 文件转换为 CSV 是实际开发中的常见场景。以下示例加载现有 Excel 文件(.xls 或 .xlsx 格式),并将其第一个工作表导出为 CSV 文件。该方法无需手动解析单元格数据,操作十分简单:
using System.Text;
using Spire.Xls;
namespace ExcelToCSV
{
class Program
{
static void Main(string[] args)
{
// 1. 加载现有Excel文件
Workbook workbook = new Workbook();
workbook.LoadFromFile("产品.xlsx");
// 2. 选择第一个工作表
Worksheet worksheet = workbook.Worksheets[0];
// 3. 将工作表另存为CSV文件
worksheet.SaveToFile("Excel转CSV.csv", ",", Encoding.UTF8);
workbook.Dispose();
Console.WriteLine($"Excel转CSV成功!");
}
}
}
自定义技巧: 可以修改 SaveToFile() 方法中的分隔符和编码参数,以满足不同地区的格式要求。
通过 Spire.XLS for .NET 组件,C# 开发者可轻松实现 CSV 文件的创建与转换。无论你是从零构建基础 CSV 文件、将集合数据映射到 CSV,还是将 Excel 文件转换为 CSV,本文均提供了详细、可落地的操作步骤。如需了解更多 .NET 中操作 Excel 或 CSV 的示例,可访问Spire.XLS 官方文档。
答:保存 CSV 时指定 Encoding.UTF8 或 Encoding.Unicode编码。
答:不能。CSV 是纯文本格式,本身不支持多工作表结构。如需处理多个数据集,可创建多个独立的CSV文件,或在保存前将多个工作表合并为一个工作表。
答:无需写入表头行,直接从第 1 行开始填充数据即可。
Spire.Doc for Java 14.1.3 现已正式发布。该版本支持为表格应用自定义样式,支持使用 removeSelf() 方法删除样式,并支持从模板文档中克隆样式。同时,一些在转换 Word 到 PDF 或 Markdown,以及更新目录(TOC)或页码域时出现的问题也得以成功修复。更多详情如下。
新功能:
document.getStyles().get("style1").removeSelf();
Document doc = new Document();
Section section = doc.addSection();
TableStyle tableStyle = (TableStyle) doc.getStyles().add(StyleType.Table_Style, "TestTableStyle1");
tableStyle.setHorizontalAlignment(RowAlignment.Center);
tableStyle.getBorders().setColor(Color.BLUE);
tableStyle.getBorders().setBorderType(BorderStyle.Single);
Table table = section.addTable();
table.resetCells(1, 1);
table.getRows().get(0).getCells().get(0).addParagraph().appendText("Aligned to the center of the page");
table.setPreferredWidth(PreferredWidth.fromPoints(300));
table.applyStyle(tableStyle);
// table.getFormat().setStyle(tableStyle);
doc.saveToFile(outputDocxFile, FileFormat.Docx);
doc.copyStylesFromTemplate(inputFile_2); // Accepts file path as String
doc.copyStylesFromTemplate(doc2); // Accepts another Document object
问题修复:
我们很高兴地宣布 Spire.Presentation for Java 11.1.1 正式发布。本版本引入了多项新功能,包括从形状中读取自定义数据以及设置音频淡入和淡出时长。此外,还修复了两个已知问题。详细信息如下。
新功能:
Presentation ppt = new Presentation();
ppt.loadFromFile(inputFile);
List dataList = ppt.getSlides().get(0).getShapes().get(0).getCustomerDataList();
System.out.println(dataList.size());
for(int i = 0; i < dataList.size(); i++)
{
String name = dataList.get(i).getName();
String content = dataList.get(i).getXML();
}
Presentation ppt = new Presentation();
ppt.loadFromFile(inputFile);
Rectangle2D.Double audioRect = new Rectangle2D.Double(220, 240, 80, 80);
IAudio audio=ppt.getSlides().get(0).getShapes().appendAudioMedia(inputFile_1, audioRect);
// 设置音频播放开始时的淡入效果持续时间为 13 秒
audio.setFadeInDuration(13000f);
// 设置音频播放结束时的淡出效果持续时间为 20 秒
audio.setFadeOutDuration(20000f);
ppt.saveToFile(outputFile, FileFormat.PPTX_2016);
ppt.dispose();
Presentation ppt = new Presentation();
ppt.loadFromFile(inputFile);
Rectangle2D.Double audioRect = new Rectangle2D.Double(220, 240, 80, 80);
IAudio audio = ppt.getSlides().get(0).getShapes().appendAudioMedia(inputFile_1, audioRect);
// 设置音频的起始裁剪时间为 8 秒
audio.setTrimFromStart(8000f);
// 设置音频的结束裁剪时间为 13 秒
audio.setTrimFromEnd(13000f);
ppt.saveToFile(outputFile, FileFormat.PPTX_2016);
ppt.dispose();
Presentation presentation = new Presentation();
presentation.loadFromFile("data/test.pptx");
Double[] widths = new Double[]{100d, 100d, 150d, 100d, 100d};
Double[] heights = new Double[]{15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d, 15d};
//添加表格
ITable table = presentation.getSlides().get(0).getShapes().appendTable((float) presentation.getSlideSize().getSize().getWidth() / 2 - 275, 90, widths, heights);
//设置范围是1-0,表格默认颜色为黑色
table.getFill().setTransparency(0.5f);
//设置具体表格颜色
table.get(0,0).getFillFormat().setFillType(FillFormatType.SOLID);
table.get(0,0).getFillFormat().getSolidColor().setColor(Color.BLUE);
presentation.saveToFile("result.pptx",FileFormat.PPTX_2016);
问题修复:
https://www.e-iceblue.cn/Downloads/Spire-Presentation-JAVA.html

在 Python 应用中,通过代码生成 Word 文档是一种非常常见的需求。无论是报表、发票、合同、审计日志,还是数据导出结果,很多场景都需要以 可编辑的 .docx 文件 形式交付,而不仅仅是纯文本或 PDF。
与简单的文本输出不同,Word 文档本质上是一个结构化文档,由节(Section)、段落(Paragraph)、样式(Style)以及各种版式规则共同组成。如果在生成 Word 文档时,仅将 .docx 当作“文本容器”来处理,往往会在内容增长后出现排版混乱、维护困难等问题。
本文将围绕 使用 Python 实际创建 Word 文档 这一主题展开,基于 Spire.Doc for Python 进行讲解,重点说明如何按照 Word 原生的文档对象模型构建内容,在正确的结构层级上应用格式与布局,并确保在文档内容不断扩展的情况下,仍然能够生成结构稳定、易于编辑的 .docx 文件。
内容概览
在开始编写代码之前,理解 Word 文档在内部是如何组织的非常重要。
.docx 文件并不是一段线性的文本流,而是由多个具有明确职责的对象层级组成,包括:
当你在 Python 中创建 Word 文档时,本质上是在通过代码显式构建这一层级结构。只有在正确的层级上添加内容和设置格式,文档的布局和行为才能保持可预测性。
Spire.Doc for Python 为这些核心概念提供了直接的抽象,使你可以按照 Word 本身的工作方式来操作文档结构,而不是通过“拼文本”的方式生成文件。
本节将演示如何使用 Spire.Doc 在 Python 中生成一个有效的 Word 文档,重点放在正确的文档结构和基本流程上。
pip install spire.doc
你也可以从官网下载并手动集成: 下载 Spire.Doc for Python
.docx 文件from spire.doc import Document, FileFormat
# 创建文档对象
document = Document()
# 添加一个节(定义页面级布局)
section = document.AddSection()
# 向节中添加段落
paragraph = section.AddParagraph()
paragraph.AppendText(
"该文档由使用 Spire.Doc for Python 生成,"
"展示创建 Word 文档基础步骤。"
)
# 保存文档
document.SaveToFile("basic_document.docx", FileFormat.Docx)
document.Close()
该示例生成了一个最小但合法的 .docx 文件,可以直接在 Microsoft Word 中打开。整体流程包括:

从技术角度来看:
使用 Spire.Doc 创建的所有 Word 文档,都遵循这一结构模式,这也是后续更高级操作的基础。
Word 文档中的文本是分层组织的,格式设置也存在明确的层级区分:
理解段落格式、字符格式与样式之间的区别,是使用 Python 创建或编辑 Word 文档的关键。
Word 文档中的所有可见文本,都必须通过段落添加。段落不仅是文本的容器,也是布局控制的基本单位。
from spire.doc import Document, HorizontalAlignment, FileFormat, Color
document = Document()
section = document.AddSection()
# 添加标题段落
title = section.AddParagraph()
title.Format.HorizontalAlignment = HorizontalAlignment.Center
title.Format.AfterSpacing = 20
title.Format.BeforeSpacing = 20
title_range = title.AppendText("月度销售报告")
title_range.CharacterFormat.FontSize = 18
title_range.CharacterFormat.Bold = True
title_range.CharacterFormat.TextColor = Color.get_LightBlue()
title_range.CharacterFormat.FontName = "黑体"
# 添加正文段落
body = section.AddParagraph()
body.Format.FirstLineIndent = 20
body_range = body.AppendText(
"本报告提供了月度销售业绩概览,"
"包括各地区和产品类别的收入趋势。"
"下方数据旨在为管理层的决策提供支持。"
)
body_range.CharacterFormat.FontSize = 12
document.SaveToFile("formatted_paragraph.docx", FileFormat.Docx)
document.Close()
生成的 Word 文档效果如下:

技术要点说明:
Paragraph.Format 控制整个段落的布局AppendText() 返回 TextRange,用于设置字符级格式样式可以将段落和字符的格式集中定义并复用,从而提高一致性和可维护性。Word 同时支持自定义样式和内置样式,使用前都需要将样式添加到文档中。
from spire.doc import (
Document, HorizontalAlignment, BuiltinStyle,
TextAlignment, ParagraphStyle, FileFormat
)
document = Document()
# 创建自定义段落样式
custom_style = ParagraphStyle(document)
custom_style.Name = "CustomStyle"
custom_style.ParagraphFormat.HorizontalAlignment = HorizontalAlignment.Center
custom_style.ParagraphFormat.TextAlignment = TextAlignment.Auto
custom_style.CharacterFormat.Bold = True
custom_style.CharacterFormat.FontSize = 20
# 继承内置标题样式
custom_style.ApplyBaseStyle(BuiltinStyle.Heading1)
# 添加样式到文档
document.Styles.Add(custom_style)
# 应用样式
title_para = document.AddSection().AddParagraph()
title_para.ApplyStyle(custom_style.Name)
title_para.AppendText("地区业绩概览")
built_in_style = document.AddStyle(BuiltinStyle.Heading2)
document.Styles.Add(built_in_style)
heading_para = document.Sections.get_Item(0).AddParagraph()
heading_para.ApplyStyle(built_in_style.Name)
heading_para.AppendText("按地区销售情况")
document.SaveToFile("document_styles.docx", FileFormat.Docx)

技术说明:
ParagraphStyle(document) 创建与文档关联的可复用样式ParagraphFormat 控制布局属性CharacterFormat 定义字体相关属性ApplyBaseStyle() 可继承 Word 内置样式的语义与行为document.Styles 后,才能在整个文档中使用使用内置样式(如 Heading 2)可以确保文档在目录生成、大纲视图等 Word 功能中保持良好兼容性。
在 Word 的文档模型中,图片是附属于段落的嵌入对象。这种设计可以确保图片与文本一起参与排版,并在内容变化时自动调整位置。
from spire.doc import Document, TextWrappingStyle, HorizontalAlignment, FileFormat
document = Document()
section = document.AddSection()
section.AddParagraph().AppendText("\r\n\r\n示例图片\r\n")
image_para = section.AddParagraph()
image_para.Format.HorizontalAlignment = HorizontalAlignment.Center
image = image_para.AppendPicture("Screen.jpg")
image.TextWrappingStyle = TextWrappingStyle.Square
image.Width = 350
image.Height = 200
image.FillTransparency(0.7)
image.HorizontalAlignment = HorizontalAlignment.Center
document.SaveToFile("document_images.docx", FileFormat.Docx)

技术细节说明:
AppendPicture() 将图片作为段落内容插入TextWrappingStyle 控制文本环绕方式Width 与 Height 设置显示尺寸FillTransparency() 设置透明度HorizontalAlignment 控制图片在段落中的对齐方式将图片插入段落中,可以确保图片尺寸变化时分页自动调整、文本编辑后排版仍然正确,同时导出为 PDF 等格式时保持相对位置一致。
更多 Word 文档图片操作介绍请查看:使用 Python 在 Word 文档中插入图片
表格常用于展示结构化数据,例如统计报表、汇总信息或对比结果。
在 Word 的内部结构中,一个表格由行(Row)、单元格(Cell)组成,而每个单元格本身仍然是段落容器,可以包含文本、图片或其他格式化内容。
from spire.doc import Document, DefaultTableStyle, FileFormat, AutoFitBehaviorType
document = Document()
section = document.AddSection()
section.AddParagraph().AppendText("\r\n\r\n示例表格\r\n")
# 表头数据
table_headers = ["地区", "产品", "销售数量", "单价(元)", "总收入(元)"]
table_data = [
["华北", "笔记本电脑", 120, 9500, 1140000],
["华北", "智能手机", 300, 5000, 1500000],
["华南", "笔记本电脑", 80, 9500, 760000],
["华南", "智能手机", 200, 5000, 1000000],
["华东", "笔记本电脑", 150, 9500, 1425000],
["华东", "智能手机", 250, 5000, 1250000],
["西南", "笔记本电脑", 100, 9500, 950000],
["西南", "智能手机", 220, 5000, 1100000]
]
# 向节中添加表格
table = section.AddTable()
table.ResetCells(len(table_data) + 1, len(table_headers))
# 填充表头
for col_index, header in enumerate(table_headers):
header_range = table.Rows[0].Cells[col_index].AddParagraph().AppendText(header)
header_range.CharacterFormat.FontSize = 14
header_range.CharacterFormat.Bold = True
# 填充表格数据
for row_index, row_data in enumerate(table_data):
for col_index, cell_data in enumerate(row_data):
data_range = table.Rows[row_index + 1].Cells[col_index].AddParagraph().AppendText(str(cell_data))
data_range.CharacterFormat.FontSize = 12
# 应用默认表格样式并自动调整列宽
table.ApplyStyle(DefaultTableStyle.ColorfulListAccent6)
table.AutoFit(AutoFitBehaviorType.AutoFitToContents)
document.SaveToFile("document_tables.docx", FileFormat.Docx)
生成的 Word 文档预览如下:

技术要点说明:
Section.AddTable() 将表格插入到节的内容流中ResetCells(rows, columns) 明确定义表格的行列结构Table.Rows[row].Cells[col] 返回一个 TableCell 对象在 Word 中,每个单元格都是一个独立的内容容器。文本始终通过段落插入,而单元格内可以包含多个段落、图片或格式化文本。这种结构使表格既可以用于简单数据展示,也可以扩展为复杂的报表布局。
如果需要更高级的表格操作(如动态生成表格、合并单元格、单元格级格式控制等),可参考完整指南: 使用 Python 在 Word 文档中创建表格
在 Word 中,页眉和页脚属于节级元素,不参与正文内容流,也不会影响正文分页。
每一个节都可以拥有独立的页眉和页脚,这使得文档不同部分可以显示不同的重复信息。
from spire.doc import Document, FileFormat, HorizontalAlignment, FieldType, BreakType
document = Document()
section = document.AddSection()
section.AddParagraph().AppendBreak(BreakType.PageBreak)
# 添加页眉
header = section.HeadersFooters.Header
header_para1 = header.AddParagraph()
header_para1.AppendText("月度销售报告").CharacterFormat.FontSize = 12
header_para1.Format.HorizontalAlignment = HorizontalAlignment.Left
header_para2 = header.AddParagraph()
header_para2.AppendText("公司名称").CharacterFormat.FontSize = 12
header_para2.Format.HorizontalAlignment = HorizontalAlignment.Right
# 添加页脚(页码)
footer = section.HeadersFooters.Footer
footer_para = footer.AddParagraph()
footer_para.Format.HorizontalAlignment = HorizontalAlignment.Center
footer_para.AppendText("第 ").CharacterFormat.FontSize = 12
footer_para.AppendField("PageNum", FieldType.FieldPage).CharacterFormat.FontSize = 12
footer_para.AppendText(" 页,共 ").CharacterFormat.FontSize = 12
footer_para.AppendField("NumPages", FieldType.FieldNumPages).CharacterFormat.FontSize = 12
footer_para.AppendText(" 页").CharacterFormat.FontSize = 12
document.SaveToFile("document_header_footer.docx", FileFormat.Docx)
document.Dispose()
生成的文档效果如下:

技术说明:
section.HeadersFooters.Header / Footer 用于访问当前节的页眉和页脚AppendField() 可插入动态字段,如当前页码和总页数页眉和页脚通常用于显示报表标题、公司信息和页码,并且在文档内容发生变化时会自动更新,同时兼容 Word、PDF 等导出格式。
更多高级示例可参考: 使用 Python 向 Word 文档中插入页眉和页脚
在 Spire.Doc for Python 中,所有页面级布局设置都通过 Section 对象进行管理。页面大小、方向和页边距均由 Section.PageSetup 控制,并对该节内的所有内容生效。
from spire.doc import PageSize, PageOrientation
section.PageSetup.PageSize = PageSize.A4()
section.PageSetup.Orientation = PageOrientation.Portrait
技术说明:
PageSetup 是节级布局配置对象PageSize 定义页面的物理尺寸Orientation 控制纵向或横向排版节中的所有段落、表格和图片都会遵循该布局设置。修改某一节的页面设置不会影响文档中的其他节,因此可以在同一文档中使用多种页面布局。
section.PageSetup.Margins.Top = 50
section.PageSetup.Margins.Bottom = 50
section.PageSetup.Margins.Left = 60
section.PageSetup.Margins.Right = 60
技术说明:
Margins 定义正文的可打印区域页边距在节级别统一生效,不需要针对单个段落单独设置,并且不会影响页眉和页脚区域。
当文档需要混合不同页面布局时,必须创建多个节。
landscape_section = document.AddSection()
landscape_section.PageSetup.Orientation = PageOrientation.Landscape
技术要点:
AddSection() 会创建并追加一个新的节通过多节结构,可以在同一 Word 文档中混合纵向与横向页面,或为不同内容区域应用不同版式。

除了可见内容之外,Word 文档还支持通过内置文档属性存储元数据。这些属性位于文档级别,不会影响页面布局或渲染效果。
document.BuiltinDocumentProperties.Title = "Monthly Sales Report"
document.BuiltinDocumentProperties.Author = "Data Analytics System"
document.BuiltinDocumentProperties.Company = "Example Corp"
技术说明:
BuiltinDocumentProperties 用于访问 Word 的标准文档属性Title、Author、Company 等文档属性常用于文件索引、搜索、文档管理系统和审计流程。除了内置属性外,Word 还支持 关键词、主题、备注、超链接基地址 等元数据,也可以通过 Document.CustomDocumentProperties 定义自定义属性。
更多内容可参考: 使用 Python 管理 Word 文档的自定义属性
在内存中构建好 Word 文档之后,最后一步是将其保存或导出为目标格式。Spire.Doc for Python 提供统一的 API 支持多种导出格式,可在不额外修改文档结构的情况下复用同一份内容。
from spire.doc import FileFormat
document.SaveToFile("output.docx", FileFormat.Docx)
document.SaveToFile("output.pdf", FileFormat.PDF)
document.SaveToFile("output.html", FileFormat.Html)
document.SaveToFile("output.rtf", FileFormat.Rtf)
导出过程会保留文档结构,包括节、表格、图片、页眉和页脚,从而在不同格式中保持一致的布局效果。完整支持的格式列表可参考: FileFormat 枚举说明
在高频或大规模生成 Word 文档的场景下,可以通过以下方式提升性能:
document.Close() 释放资源当需要批量生成结构相同但数据不同的文档时,邮件合并(Mail Merge) 通常比逐个手动插入内容更高效。Spire.Doc for Python 内置了邮件合并功能,适用于大规模文档生成场景。
参考示例: 使用 Python 通过邮件合并批量生成 Word 文档
在通过代码生成 Word 文档的过程中,以下问题较为常见,尤其容易出现在对 Word 文档结构理解不足的情况下。
问题表现: 随着内容长度变化,原有格式被破坏,排版不可控。
改进建议: 始终基于节(Section)、段落(Paragraph)和样式(Style)来构建文档结构,而不是简单地插入原始文本。
问题表现: 当需要调整整体版式或字体风格时,必须在多个代码位置逐一修改,维护成本高。
改进建议: 通过样式和节级布局配置集中管理格式规则,避免在业务代码中重复定义格式细节。
问题表现: 修改页边距或页面方向后,意外影响了整个文档的布局。
改进建议: 使用多个节来隔离不同的页面布局设置,确保各部分互不干扰。
使用 Python 创建 Word 文档 并不仅仅是向文件中写入文本。.docx 文件本质上是由节、段落、样式以及各种嵌入对象组成的结构化文档。
通过 Spire.Doc for Python,并按照 Word 原生的文档模型来组织代码,你可以生成结构清晰、可编辑性良好、且在内容和布局变化时依然稳定的 Word 文档。这种方式尤其适合后端服务、报表生成流程以及文档自动化系统。
在涉及大型文档生成或文档转换等场景时,通常需要使用**授权版本**以获得完整功能支持。
Spire.Doc for Python 14.1.0 现已正式发布。该版本新增了用于操作和删除表格样式的接口。此外还修复了一个 启用修订并替换内容,结果不正确的问题。详情请查阅以下内容。
优化:
旧命名(已废弃):from spire.doc.charts import ChartType
新命名(请使用):from spire.doc.charts.ChartType import ChartType
新功能:
doc = Document()
doc.LoadFromFile(inputFile)
firstColumn = doc.Bookmarks["t_insert"].FirstColumn
lastColumn = doc.Bookmarks["t_insert"].LastColumn
doc = Document()
tableStyle = doc.Styles.Add(StyleType.TableStyle, "TestTableStyle3")
tableStyle.LeftIndent = 55
tableStyle.Borders.Color = Color.get_Green()
tableStyle.HorizontalAlignment = RowAlignment.Right
tableStyle.Borders.BorderType = BorderStyle.Single
section = doc.AddSection()
table = section.AddTable()
table.ResetCells(3, 3)
table.Rows[0].Cells[0].AddParagraph().AppendText("Aligned according to left indent")
table.PreferredWidth = PreferredWidth.FromPoints(300)
table.Format.StyleName = "TestTableStyle3"
style = doc.Styles.FindByName("TestTableStyle3")
if (style is not None) and isinstance(style, TableStyle):
tableStyle = style
tableStyle.Borders.Color = Color.get_Black()
tableStyle.Borders.BorderType = BorderStyle.Double
tableStyle.RowStripe = 3
tableStyle.ConditionalStyles[TableConditionalStyleType.OddRowStripe].Shading.BackgroundPatternColor = Color.get_LightBlue()
tableStyle.ConditionalStyles[TableConditionalStyleType.EvenRowStripe].Shading.BackgroundPatternColor = Color.get_LightCyan()
tableStyle.ColumnStripe = 1
tableStyle.ConditionalStyles[TableConditionalStyleType.EvenColumnStripe].Shading.BackgroundPatternColor = Color.get_LightPink()
table.ApplyStyle(tableStyle)
table.Format.StyleOptions = table.Format.StyleOptions | TableStyleOptions.ColumnStripe
doc.SaveToFile(outputFile, FileFormat.Docx)
style = doc.Styles.FindByName("TestTableStyle3")
style.RemoveSelf()
问题修复:
Spire.PDF 12.1.0 现已正式发布。该版本增强了 PDF 到 Word 的转换功能。同时,一些在 PDF 转 PDF/A-3B、HTML 转 PDF 以及获取文本框域字体属性时出现的问题也得以成功修复。此外,该版本还优化了时间戳服务器的请求效率。更多详情如下。
问题修复:
Spire.Doc 14.1.3 现已发布。本次更新重点修复了在文档布局处理和 Word 转 PDF 过程中程序长时间挂起的问题,并解决了列表编号获取及内容转换不正确等相关问题,进一步提升了整体稳定性和转换准确性。更新内容如下:
问题修复:
Spire.Presentation for Python 11.1.0现已发布,此更新解决了两个特定的PPTX到PDF问题,并修复了另外两个已知的Bug。详细信息如下。
问题修复:
https://www.e-iceblue.cn/Downloads/Spire-Presentation-Python.html