我是编程新手,我正在尝试将Windows窗体中的datagriedview的值导出为PDF。 但是,当我执行此代码时,它会在foreach上使我的执行崩溃,在这里我可以正确获得单元格值(PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Value.ToString()));)有人可以帮助我使用此代码吗? / p>
private void button1_Click(object sender, EventArgs e)
{
PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 30;
pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
pdfTable.DefaultCell.BorderWidth = 1;
foreach (DataGridViewColumn column in dataGridView1.Columns)
{
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
cell.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Value.ToString()));
pdfTable.AddCell(pdfCell);
}
}
string folderPath = "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();
}
}