C# 如何把DataGridView导入到PDF表格
要实现将DataGridView导入到PDF表格需要借助第三方PDF控件,本文主要介绍如何使用Free Spire.PDF控件把数据从DataGridView导入到PDF文档的表格中。Free Spire.PDF是一款免费专业的.NET PDF控件,它提供给开发人员一系列丰富的PDF功能,例如读、写、新建、编辑、转换和打印等。
DataGridView导入到PDF表格
首先创建一个WinForm应用程序,命名为DataGridViewToPDF,然后引用Free Spire.PDF安装文件夹下对应的dll文件到项目中。以下代码示例将介绍如何使用Free Spire.PDF将DataGridView中的数据导入到PDF表格中。这里我创建了一个虚拟的DataGridView用于测试。
private void button1_Click(object sender, EventArgse)
{
//创建一个DataTable并将数据添加到DataGridView
DataTable datatable = new DataTable();
datatable.Columns.Add("学号", typeof(string));
datatable.Columns.Add("姓名", typeof(string));
datatable.Columns.Add("年龄", typeof(int));
datatable.Columns.Add("籍贯", typeof(string));
datatable.Columns.Add("生日", typeof(string));
datatable.Rows.Add(new object[] { "01001", "张丽娟", "17", "四川", "2000/7/15"});
datatable.Rows.Add(new object[] { "01002", "王小鹏", "18", "云南", "1999/2/13"});
datatable.Rows.Add(new object[] { "01003", "吴萍萍", "17", "天津", "2000/7/15"});
datatable.Rows.Add(new object[] { "01004", "宋晓宇", "18", "四川", "1999/2/13"});
datatable.Rows.Add(new object[] { "01005", "李凯", "17", "河北", "2000/7/15"});
datatable.Rows.Add(new object[] { "01006", "杨媛媛", "18", "重庆", "1999/2/13"});
datatable.Rows.Add(new object[] { "01007", "刘小辉", "17", "浙江", "2000/7/15"});
datatable.Rows.Add(new object[] { "01008", "曹晴", "18", "新疆", "1999/2/13"});
datatable.Rows.Add(new object[] { "01009", "段军", "17", "黑龙江", "2000/7/15"});
datatable.Rows.Add(new object[] { "010010", "刘琦琦", "18", "北京", "1999/2/13"});
dataGridView1.DataSource = datatable;
//新建PDF文档
PdfDocument pdf = new PdfDocument();
//添加页面
PdfPageBase page =pdf.Pages.Add();
//创建表格
PdfTable table = new PdfTable();
//将DataGridView的数据导入到表格
table.DataSource = dataGridView1.DataSource;
//显示表头(默认为不显示)
table.Style.ShowHeader = true;
//设置单元格内容与边框的间距
table.Style.CellPadding = 2;
//设置表格的布局 (超过一页自动将表格续写到下一页)
PdfTableLayoutFormat tableLayout = new PdfTableLayoutFormat();
tableLayout.Break = PdfLayoutBreakType.FitElement;
tableLayout.Layout = PdfLayoutType.Paginate;
//添加自定义事件
table.BeginRowLayout += newBeginRowLayoutEventHandler(table_BeginRowLayout);
//将表格绘制到页面并指定绘制的位置和范围
table.Draw(page, new RectangleF(10, 50, 300, 300), tableLayout);
pdf.SaveToFile("Output.pdf");
}
//在自定义事件中设置单元格字体和文本对齐方式
private static void table_BeginRowLayout(objectsender, BeginRowLayoutEventArgs args)
{
PdfCellStyle cellstyle = new PdfCellStyle();
cellstyle.StringFormat = new PdfStringFormat(PdfTextAlignment.Center);
cellstyle.Font = new PdfTrueTypeFont(new Font("Arial Unicode MS", 9f), true);
args.CellStyle = cellstyle;
}
DataGridView:
导入到PDF表格: