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

查看:35
本文介绍了使用 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);

现在您只添加了一次表格.

Now you are adding the table only once.

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

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