【问题标题】:How to convert data from dataGridView to a PDF file?如何将 dataGridView 中的数据转换为 PDF 文件?
【发布时间】:2017-08-28 00:58:11
【问题描述】:

我有这个 dataGridView,我想将其转换为 PDF 文件。我该怎么做?我在网上搜索并找到了一些代码,但我发现的网站似乎遗漏了很多东西。

using System.IO;
using System.Data;
using System.Reflection;
using iTextSharp.text.pdf;
using iTextSharp.text;

private void btnExportPdf_Click(object sender, EventArgs e)
{
    //Creating iTextSharp Table from the DataTable data
    PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
    pdfTable.DefaultCell.Padding = 3;
    pdfTable.WidthPercentage = 30;
    pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
    pdfTable.DefaultCell.BorderWidth = 1;

    //Adding Header row
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
        cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
        pdfTable.AddCell(cell);
    }

    //Adding DataRow
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            pdfTable.AddCell(cell.Value.ToString());
        }
    }

    //Exporting to PDF
    string folderPath = "C:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
        Directory.CreateDirectory(folderPath);
    }
    using (FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create))
    {
        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, stream);
        pdfDoc.Open();
        pdfDoc.Add(pdfTable);
        pdfDoc.Close();
        stream.Close();
    }
}

【问题讨论】:

    标签: c# winforms pdf datagridview


    【解决方案1】:

    我转换了这个:

        //Adding DataRow
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            foreach (DataGridViewCell cell in row.Cells)
            {
                pdfTable.AddCell(cell.Value.ToString());
            }
        }
        TO:
        //Adding DataRow
    
    
         foreach (DataGridViewRow row in dataGridView1.Rows)
         {
              foreach (DataGridViewCell cell in row.Cells)
              {
                   try
                   {
                       pdfTable.AddCell(cell.Value.ToString());
                   }
                   catch { }
               }
         }
    

    在我下载的新版本中,这必须更改:

    cell.BackgroundColor = new iTextSharp.text.Color(240, 240, 240);
    

    到:

    cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-06
      • 1970-01-01
      • 2013-07-11
      • 2016-07-10
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多