表格是一种直观高效的数据展示方式,可以按行和列的形式呈现数据,从而更容易吸引读者的注意。相比于普通文本内容,表格能够更清晰地反映数据之间的关系,降低阅读难度,加深读者对数据的理解。本文将介绍如何使用 Spire.PDF for .NET 通过 .NET 程序在 PDF 文档中创建表格。
Spire.PDF for .NET 提供了 PdfTable 和 PdfGrid 类来处理 PDF 文档中的表格。PdfTable 类用于快速创建简单常规而没有太多格式的表格。而 PdfGrid 类则用于创建更复杂的表格。
下表列出了这两个类之间的区别。
| PdfTable | PdfGrid | |
| 格式设置 | ||
| 行 | 可通过事件设置, 无 API 支持。 | 可通过 API 设置。 | 
| 列 | 可通过 API 设置(StringFormat)。 | 可通过 API 设置(StringFormat)。 | 
| 单元格 | 可通过事件设置 ,无 API 支持。 | 可通过 API 设置。 | 
| 其他 | ||
| 跨列合并 | 不支持。 | 可通过 API 设置。 | 
| 跨行合并 | 可通过事件设置 ,无 API 支持。 | 可通过 API 设置。 | 
| 嵌套表格 | 可通过事件设置 ,无 API 支持。 | 可通过 API 设置。 | 
| 事件 | BeginCellLayout, EndCellLayout, BeginRowLayout, EndRowLayout, BeginPageLayout, EndPageLayout. | BeginPageLayout, EndPageLayout. | 
以下两部分分别介绍如何使用 PdfTable 类和 PdfGrid 类在 PDF 文档中创建表格:
安装 Spire.PDF for .NET
首先,您需要添加 Spire.PDF for .NET 包中包含的 DLL 文件作为 .NET 项目中的引用。DLL 文件可以从此链接下载或通过 NuGet 安装。
PM> Install-Package Spire.PDF使用 PdfTable 类在 PDF 文档中创建表格
以下是使用 PdfTable 类在 PDF 文档中创建表格的详细操作步骤:
- 创建一个 PdfDocument 的对象。
- 使用 PdfDocument.Pages.Add() 方法在 PDF 文档中添加一个页面。
- 创建一个 Pdftable 的对象。
- 通过 PdfTable.Style 属性设置表格样式。
- 通过 PdfTable.DataSource 属性插入数据到表格中。
- 通过 BeginRowLayout 事件设置行高和行的背景色。
- 使用 PdfTable.Draw() 方法在 PDF 页面上绘制表格。
- 使用 PdfDocument.SaveToFile() 方法保存 PDF 文档。
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Tables;
using System;
using System.Data;
using System.Drawing;
namespace CreatePDFTable
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //创建一个PdfDocument的对象
            PdfDocument doc = new PdfDocument();
            //添加一个页面
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));
            //创建一个PdfTable的对象
            PdfTable table = new PdfTable();
            //设置表头以及其他单元格的字体
            table.Style.DefaultStyle.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC", 12f, FontStyle.Regular), true);
            table.Style.HeaderStyle.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC Medium", 12f, FontStyle.Bold), true);
            //创建一个DataTable的对象
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("编号");
            dataTable.Columns.Add("姓名");
            dataTable.Columns.Add("部门");
            dataTable.Columns.Add("职位");
            dataTable.Columns.Add("等级");
            dataTable.Rows.Add(new string[] { "1", "大卫", "信息部", "经理", "1" });
            dataTable.Rows.Add(new string[] { "3", "朱颖", "人事部", "经理", "1" });
            dataTable.Rows.Add(new string[] { "4", "苏菲", "市场部", "经理", "1" });
            dataTable.Rows.Add(new string[] { "7", "维奇", "市场部", "销售代表", "2" });
            dataTable.Rows.Add(new string[] { "9", "韦恩", "人事部", "人力资源主管", "2" });
            dataTable.Rows.Add(new string[] { "11", "米雅", "开发部", "开发人员", "2" });
            //将数据表设置为表格的数据源
            table.DataSource = dataTable;
            //显示表头(表头默认隐藏)
            table.Style.ShowHeader = true;
            //设置表头的字体颜色和背景色
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray;
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White;
            //设置表头的文本对齐方式
            table.Style.HeaderStyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            //设置其他单元格的文本对齐方式
            for (int i = 0; i < table.Columns.Count; i++)
            {
                table.Columns[i].StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
            }
            //订阅事件
            table.BeginRowLayout += Table_BeginRowLayout;
            //将表格绘制在页面上
            table.Draw(page, new PointF(0, 30));
            //保存PDF文档
            doc.SaveToFile("PdfTable.pdf");
            doc.Dispose();
        }
        //事件处理器
        private static void Table_BeginRowLayout(object sender, BeginRowLayoutEventArgs args)
        {
            //设置行高
            args.MinimalHeight = 20f;
            //交替行的背景色
            if (args.RowIndex < 0)
            {
                return;
            }
            if (args.RowIndex % 2 == 1)
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray;
            }
            else
            {
                args.CellStyle.BackgroundBrush = PdfBrushes.White;
            }
        }
    }
}Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Tables
Imports System
Imports System.Data
Imports System.Drawing
Namespace CreatePDFTable
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            '创建一个PdfDocument的对象
            Dim doc As PdfDocument = New PdfDocument()
            '添加一个页面
            Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(40))
            '创建一个PdfTable的对象
            Dim table As PdfTable = New PdfTable()
            '设置表头以及其他单元格的字体
            table.Style.DefaultStyle.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC", 12.0F, FontStyle.Regular), True)
            table.Style.HeaderStyle.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC Medium", 12.0F, FontStyle.Bold), True)
            '创建一个DataTable的对象
            Dim dataTable As DataTable = New DataTable()
            dataTable.Columns.Add("编号")
            dataTable.Columns.Add("姓名")
            dataTable.Columns.Add("部门")
            dataTable.Columns.Add("职位")
            dataTable.Columns.Add("等级")
            Dim String() As DataTable.Rows.Add(New
            {
            	 "1", "大卫", "信息部", "经理", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "3", "朱颖", "人事部", "经理", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "4", "苏菲", "市场部", "经理", "1" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "7", "维奇", "市场部", "销售代表", "2" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "9", "韦恩", "人事部", "人力资源主管", "2" 
            }
)
            Dim String() As DataTable.Rows.Add(New
            {
            	 "11", "米雅", "开发部", "开发人员", "2" 
            }
)
 
            '将数据表设置为表格的数据源
            table.DataSource = dataTable
            '显示表头(表头默认隐藏)
            table.Style.ShowHeader = True
            '设置表头的字体颜色和背景色
            table.Style.HeaderStyle.BackgroundBrush = PdfBrushes.Gray
            table.Style.HeaderStyle.TextBrush = PdfBrushes.White
            '设置表头的文本对齐方式
            table.Style.HeaderStyle.StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
            '设置其他单元格的文本对齐方式
            Dim i As Integer
            For i = 0 To table.Columns.Count - 1 Step i + 1
                table.Columns(i).StringFormat = New PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle)
            Next
            '订阅事件
            table.BeginRowLayout += Table_BeginRowLayout()
            '将表格绘制在页面上
            table.Draw(page, New PointF(0, 30))
            '保存PDF文档
            doc.SaveToFile("PdfTable.pdf")
            doc.Dispose()
        End Sub
        '事件处理器
        Private Shared Sub Table_BeginRowLayout(ByVal sender As Object, ByVal args As BeginRowLayoutEventArgs)
            '设置行高
            args.MinimalHeight = 20.0F
            '交替行的背景色
            If args.RowIndex < 0 Then
                Return
            End If
            If args.RowIndex % 2 = 1 Then
                args.CellStyle.BackgroundBrush = PdfBrushes.LightGray
            Else
                args.CellStyle.BackgroundBrush = PdfBrushes.White
            End If
        End Sub
    End Class
End Namespace
使用 PdfGrid 类在 PDF 文档中创建表格
下面是使用 PdfGrid 类在 PDF 文档中创建表格的详细操作步骤:
- 创建一个 PdfDocument 的对象。
- 使用 PdfDocument.Pages.Add() 方法在 PDF 文档中添加一个页面。
- 创建一个 PdfGrid 对象。
- 通过 PdfGrid.Style 属性设置表格样式。
- 使用 PdfGrid.Rows.Add() 方法为表格添加行。
- 通过 PdfGridRow.Cells[index].Value 属性插入数据到指定单元格。
- 通过 PdfGridRow.RowSpan 或 PdfGridRow.ColumnSpan 属性跨列或跨行合并单元格。
- 通过 PdfGridRow.Cells[index].StringFormat 和 PdfGridRow.Cells[index].Style 属性设置指定单元格的格式。
- 使用 PdfGrid.Draw() 方法在 PDF 页面上绘制表格。
- 使用 PdfDocument.SaveToFile() 方法保存 PDF 文档。
- C#
- VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
using System;
using System.Drawing;
namespace CreatePDFGrid
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //创建一个PdfDocument的对象
            PdfDocument doc = new PdfDocument();
            //添加一个页面
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(40));
            //创建一个PdfGrid的对象
            PdfGrid grid = new PdfGrid();
            //设置单元格填充
            grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
            //设置字体
            grid.Style.Font = new PdfTrueTypeFont(new Font("HarmonyOS Sans SC", 13f, FontStyle.Regular), true);
            //添加行
            PdfGridRow row1 = grid.Rows.Add();
            PdfGridRow row2 = grid.Rows.Add();
            PdfGridRow row3 = grid.Rows.Add();
            PdfGridRow row4 = grid.Rows.Add();
            grid.Columns.Add(4);
            //获取列宽
            foreach (PdfGridColumn col in grid.Columns)
            {
                col.Width = 110f;
            }
            //写入数据到指定单元格
            row1.Cells[0].Value = "订单及支付状态";
            row2.Cells[0].Value = "订单号";
            row2.Cells[1].Value = "日期";
            row2.Cells[2].Value = "顾客姓名";
            row2.Cells[3].Value = "是否已支付";
            row3.Cells[0].Value = "00223";
            row3.Cells[1].Value = "2022年06月02日";
            row3.Cells[2].Value = "专相地产";
            row3.Cells[3].Value = "已支付";
            row4.Cells[0].Value = "00224";
            row4.Cells[1].Value = "2022年06月03日";
            row4.Cells[3].Value = "未支付";
            //跨列合并单元格
            row1.Cells[0].ColumnSpan = 4;
            //跨行合并单元格
            row3.Cells[2].RowSpan = 2;
            //设置指定单元格的文本对齐方式
            row1.Cells[0].StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            row3.Cells[2].StringFormat = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle);
            //设置指定单元格的背景色
            row1.Cells[0].Style.BackgroundBrush = PdfBrushes.Orange;
            row4.Cells[3].Style.BackgroundBrush = PdfBrushes.LightGray;
            //设置边框格式
            PdfBorders borders = new PdfBorders();
            borders.All = new PdfPen(Color.Orange, 0.8f);
            foreach (PdfGridRow pgr in grid.Rows)
            {
                foreach (PdfGridCell pgc in pgr.Cells)
                {
                    pgc.Style.Borders = borders;
                }
            }
            //将表格绘制在页面上
            grid.Draw(page, new PointF(0, 30));
            //保存PDF文档
            doc.SaveToFile("PdfGrid.pdf");
            doc.Dispose();
        }
    }
}Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Grid
Imports System
Imports System.Drawing
Namespace CreatePDFGrid
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            '创建一个PdfDocument的对象
            Dim doc As PdfDocument = New PdfDocument()
            '添加一个页面
            Dim page As PdfPageBase = doc.Pages.Add(PdfPageSize.A4, New PdfMargins(40))
            '创建一个PdfGrid的对象
            Dim grid As PdfGrid = New PdfGrid()
            '设置单元格填充
            grid.Style.CellPadding = New PdfPaddings(1, 1, 1, 1)
            '设置字体
            grid.Style.Font = New PdfTrueTypeFont(New Font("HarmonyOS Sans SC", 13.0F, FontStyle.Regular), True)
            '添加行
            Dim row1 As PdfGridRow = grid.Rows.Add()
            Dim row2 As PdfGridRow = grid.Rows.Add()
            Dim row3 As PdfGridRow = grid.Rows.Add()
            Dim row4 As PdfGridRow = grid.Rows.Add()
            grid.Columns.Add(4)
            '获取列宽
            Dim col As PdfGridColumn
            For Each col In grid.Columns
                col.Width = 110.0F
            Next
            '写入数据到指定单元格
            row1.Cells(0).Value = "订单及支付状态"
            row2.Cells(0).Value = "订单号"
            row2.Cells(1).Value = "日期"
            row2.Cells(2).Value = "顾客姓名"
            row2.Cells(3).Value = "是否已支付"
            row3.Cells(0).Value = "00223"
            row3.Cells(1).Value = "2022年06月02日"
            row3.Cells(2).Value = "专相地产"
            row3.Cells(3).Value = "已支付"
            row4.Cells(0).Value = "00224"
            row4.Cells(1).Value = "2022年06月03日"
            row4.Cells(3).Value = "未支付"
            '跨列合并单元格
            row1.Cells(0).ColumnSpan = 4
            '跨行合并单元格
            row3.Cells(2).RowSpan = 2
            '设置指定单元格的文本对齐方式
            row1.Cells(0).StringFormat = New PdfStringFormat(PdfTextAlignment.Center)
            row3.Cells(2).StringFormat = New PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Middle)
            '设置指定单元格的背景色
            row1.Cells(0).Style.BackgroundBrush = PdfBrushes.Orange
            row4.Cells(3).Style.BackgroundBrush = PdfBrushes.LightGray
            '设置边框格式
            Dim borders As PdfBorders = New PdfBorders()
            borders.All = New PdfPen(Color.Orange, 0.8F)
            Dim pgr As PdfGridRow
            For Each pgr In grid.Rows
                Dim pgc As PdfGridCell
                For Each pgc In pgr.Cells
                    pgc.Style.Borders = borders
                Next
            Next
            '将表格绘制在页面上
            grid.Draw(page, New PointF(0, 30))
            '保存PDF文档
            doc.SaveToFile("PdfGrid.pdf")
            doc.Dispose()
        End Sub
    End Class
End Namespace
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。
 
    


 
					



