【发布时间】:2015-01-15 14:26:55
【问题描述】:
我正在编写一个简单的应用程序,允许用户在 itextsharp 参考的帮助下将创建的数据网格(此处为它的 dataGridView1)导出到 pdf 文件。 我在互联网上找到了一个有用的示例代码,但我在配置它以导出用户在使用应用程序期间输入的数据时遇到了一些问题。用户在文本框中输入数据,将其保存到数据网格中。 结果 pdf 文件仅包含从文本框中获取的标题,没有单元格内容(用户使用文本框输入和保存的数据)。
这里是代码
//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.BaseColor(240, 240, 240);
pdfTable.AddCell(cell);
}
//Exporting to PDF
string folderPath = "C:\\Users\\Marcus\\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();
}
}
【问题讨论】:
-
在
foreach循环中添加另一个循环,该循环实际上遍历每一行。并将单元格值添加到 pdfTable。很明显new PdfPcell(new Phrase(column.HeaderText));只会抓取标题 -
你能给我一个示例循环吗?
-
foreach(DataGridViewRow row in dataGridView1.rows) { foreach(DataGridViewCell cell in row.cells) { PdfPCell cell = new PdfPCell(new Phrase(cell.Value)); } } -
实际上只是在当前 foreach 循环之后添加该循环。不要嵌套它。
-
你确定吗?它说“不能在此范围内声明名为'cell'的局部变量,因为它会给'cell'赋予不同的含义,它已经在'父或当前'范围中用于表示其他东西”和'iTextSharp。 text.pdf.PdfPCell' 不包含'Value' 的定义,并且找不到接受'iTextSharp.text.pdf.PdfPCell' 类型的第一个参数的扩展方法'Value'(您是否缺少 using 指令或程序集参考?)