我尝试将c#中的gridview表导出为PDF文件。我已经搜索了其他解决方案,似乎每个人都试图首先从SQL数据库填充表。这一步是不必要的,因为我已经通过活动目录和soforth填充了表。目前我的代码可以使用,但它是纯黑色和白色的,看起来相当沉闷。
这是我当前的代码(使用iTextSharp):
protected void ExportToPDF()
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdvList.AllowPaging = false;
// grdvList.DataBind();
grdvList.RenderBeginTag(hw);
grdvList.HeaderRow.RenderControl(hw);
foreach (GridViewRow row in grdvList.Rows)
{
row.RenderControl(hw);
}
grdvList.FooterRow.RenderControl(hw);
grdvList.RenderEndTag(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
我的网格视图:
<asp:GridView ID="grdvList" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Name" datafield="Name" ReadOnly="True" >
<ItemStyle Width="17.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Phone Ext" datafield="Phone Ext" ReadOnly="True" >
<ItemStyle Width="11.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Mobile" datafield="Mobile" ReadOnly="True" >
<ItemStyle Width="16%" />
</asp:BoundField>
<asp:BoundField HeaderText="Email" datafield="Email" ReadOnly="True" >
<ItemStyle Width="47.5%" />
</asp:BoundField>
<asp:BoundField HeaderText="Department" DataField="Department" ReadOnly="True" >
<ItemStyle Width="17.5%" />
</asp:BoundField>
</Columns>
<alternatingrowstyle backcolor="#D6D6D6" />
</asp:GridView>
我想为所有表格单元格添加边框,使每个第二行都具有灰色背景。它在我的网页上工作得很好,但我也需要它在我的PDF文档中工作。有人可以帮忙吗?
答案 0 :(得分:0)
尝试在aspx中使用gridview中的Alternaterowcolors,如下所示,
1. Alternative color for Gridview rows
</div>
<br />
<asp:GridView ID="GridVwRowcolorchange" runat="server" AutoGenerateColumns="False"
Font-Names="Verdana" PageSize="5" Width="75%" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px">
<AlternatingRowStyle BackColor="#BFE4FF" />
<PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
<HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="15px" BorderColor="#CCCCCC"
BorderStyle="Solid" BorderWidth="1px" />
<RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
BorderWidth="1px" />
<Columns>
<asp:BoundField DataField="Emp_Name" HeaderText="Employee Name" />
<asp:BoundField DataField="Emp_id" HeaderText="Employee ID" />
<asp:BoundField DataField="Emp_job" HeaderText="Job title" />
<asp:BoundField DataField="Emp_Dep" HeaderText="Department" />
</Columns>
</asp:GridView>