我只是想用itextSharp導出網格視圖數據。這裏是我的代碼如何將網格視圖導出爲Excel有辦法使用此技術並使用itextSharp創建表。如何使用itext將網格視圖數據導出爲pdf
這是我的代碼:
protected void ibtnxls1_Click(object sender, ImageClickEventArgs e)
{
DataTable dt = (DataTable)Session["PostTable"];
string fileName = DateTime.Now.ToString("ddMMyyyy_HHmmss");
string attachment = "attachment; filename=" + fileName + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "applicssssation/vnd.ms-excel";
string sTab = "";
foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(sTab + dc.ColumnName);
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr1 in dt.Rows)
{
sTab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(sTab + dr1[i].ToString());
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
我有這個屏幕截圖如下答案:
該解決方案對我的作品:
DataTable dt = (DataTable)Session["PostTable"];
iTextSharp.text.Table table = new iTextSharp.text.Table(dt.Columns.Count);
table.Cellpadding = 2;
table.Width = 100;
//Transfer rows from GridView to table
for (int i = 0; i < dt.Columns.Count; i++)
{
string cellText = Server.HtmlDecode(dt.Columns[i].ToString());
iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#FFFFFF"));
table.AddCell(cell);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int j = 0; j < dt.Columns.Count; j++)
{
string cellText = Server.HtmlDecode(dt.Rows[i][j].ToString());
iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
//Set Color of Alternating row
if (i % 2 != 0)
{
cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#FFFFFF"));
}
table.AddCell(cell);
}
}
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
pdfDoc.Add(table);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" +
"filename=" + DateTime.Now.ToString("ddMMyyyy_HHmmss") + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
你想將你的數據導出爲excel還是pdf? –
這是我如何將網格視圖數據導出爲excel的代碼示例,現在我只是想使用此邏輯導出爲pdf。 – Shal