使用itextsharp将dataGridView转换为pdf [英] dataGridView to pdf with itextsharp

查看:179
本文介绍了使用itextsharp将dataGridView转换为pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试获取dataGridView中特定列的值时遇到问题,并将它们添加到PdtPtable中。
但是表中添加的值会重复,例如第一行会添加两次。我试图遍历每一行和每一行中的每一行。

I have a problem while trying to get values of specific columns in dataGridView and add them to the PdtPtable. But the values added in the table is repeated, for example row one is added twice.I tried to go through each row and in every row through each column.

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        try {
            pdfTable.AddCell(celli.Value.ToString());
        }
        catch { }
    }
    doc.Add(pdfTable);
}


推荐答案

我修复了缩进你的代码片段。你现在可以一眼就看出你做错了什么。

I have fixed the indentation in your code snippet. You can now see what you're doing wrong in one glimpse.

你有:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        try {
            pdfTable.AddCell(celli.Value.ToString());
        }
        catch { }
    }
    doc.Add(pdfTable);
}

这意味着您要创建一个表,并将其添加多次是行,因此重复行。

This means that you are creating a table, adding it as many times as there are rows, hence the repetition of the rows.

你应该有:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        try {
            pdfTable.AddCell(celli.Value.ToString());
        }
        catch { }
    }
}
doc.Add(pdfTable);

或者更好:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        pdfTable.AddCell(celli.Value.ToString());
    }
}
doc.Add(pdfTable);

现在只添加一次表。

这篇关于使用itextsharp将dataGridView转换为pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆