【发布时间】:2023-01-14 01:37:07
【问题描述】:
我能够将完整的 gridview 导出为 pdf,但我无法理解如何定位特定行并在单击按钮时使用 itextsharp 将其导出为 pdf
下面是我导出为 pdf 的代码,我可以在其中导出完整的 gridview
private void gvSamplereports_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == gvSamplereports.Columns["btnPDFsingle"].Index)
{
DateTime PrintTime = DateTime.Now;
if (gvSamplereports.Rows.Count > 0)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PDF (*.pdf)|*.pdf";
sfd.FileName = "SampleDataReports_" + PrintTime.ToShortDateString() + ".pdf";
bool fileError = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
if (File.Exists(sfd.FileName))
{
try
{
File.Delete(sfd.FileName);
}
catch (IOException ex)
{
fileError = true;
MessageBox.Show("It wasn't possible to write the data to the disk." + ex.Message);
}
}
if (!fileError)
{
try
{
PdfPTable pdfTable = new PdfPTable(gvSamplereports.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;
//Below line is to add the header column name on each page of pdf
pdfTable.HeaderRows = 1;
foreach (DataGridViewColumn column in gvSamplereports.Columns)
{
Font fon = FontFactory.GetFont("ARIAL", 6);
fon.SetStyle(1);
PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText, fon));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
pdfTable.AddCell(cell);
}
foreach (DataGridViewRow row in gvSamplereports.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
Font fon = FontFactory.GetFont("ARIAL", 6);
PdfPCell cell2 = new PdfPCell(new Phrase(cell.Value?.ToString(), fon));
cell2.HorizontalAlignment = Element.ALIGN_CENTER;
pdfTable.AddCell(cell2);
//pdfTable.AddCell(cell.Value.ToString());
}
}
using (FileStream stream = new FileStream(sfd.FileName, FileMode.Create))
{
Document pdfDoc = new Document(PageSize.A4, 30f, 30f, 100f, 50f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
//PDFFooter is class created for adding header and footer in the pdf
writer.PageEvent = new PDFFooter();
pdfDoc.Open();
pdfDoc.Add(pdfTable);
pdfDoc.Close();
stream.Close();
}
MessageBox.Show("Data Exported Successfully !!!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Error :" + ex.Message);
}
}
}
}
else
{
MessageBox.Show("No Record To Export !!!", "Info");
}
}
}
我添加了图像以供参考,单击按钮后,我想使用 c# winform 中的 Itextsharp 以 pdf 格式导出带有标题列名称的单行,以 pdf 格式导出的数据应如下图所示
【问题讨论】:
-
不要打电话给
DataGridViewaGridView或DataGrid,反之亦然!!这是错误和令人困惑的,因为它们是不同的控件。总是用他们的名字来称呼事物正确的名称! - 目前你正在遍历所有行。为什么?除了包含太多行之外,结果还好吗? - 要限制到带有单击按钮的行,只需不要循环,而是使用 e.RowIndex 访问单击的行。 -
谢谢你的回复,你能用任何例子或任何文章帮助我吗我如何使用 e.RowIndex 而不是循环,itextsharp 对我来说是一个新概念所以我无法想象如何使用 e.RowIndex @TaW
-
这与 iTextSharp 无关。这完全是关于你的循环:将
foreach (DataGridViewRow row in gvSamplereports.Rows)替换为DataGridViewRow row = gvSamplereports.Rows[e.RowIndex]!