我正在尝试使用包iTextSharp将gridview导出为pdf。
我在我的.aspx文件中这样做:
<form id="formOptions" runat="server">
[...]
<asp:GridView ID="gvReportingStockComp" runat="server" AutoGenerateColumns="false" Visible="true">
<Columns>
<asp:BoundField DataField="cod_wo" HeaderText="N° OF" />
<asp:BoundField DataField="composant" HeaderText="Composant" />
<asp:BoundField DataField="BESOIN" HeaderText="Besoin/OF" />
<asp:BoundField DataField="BESOIN_T" HeaderText="Besoin total" />
<asp:BoundField DataField="stock_dispo" HeaderText="Stock dispo" />
<asp:BoundField DataField="QTE_RESTANTE" HeaderText="Qte restante" />
</Columns>
</asp:GridView>
</form>
在我的代码背后,我填写了gridview:
OracleConnection oConnexion = new OracleConnection();
oConnexion.ConnectionString = "X";
oConnexion.Open();
string reqStockCompTotal = "intitulé de ma requete"
OracleCommand cmdReqStockComp = new OracleCommand(reqStockCompTotal);
cmdReqStockComp.Connection = oConnexion;
OracleDataReader readerReqStockComp = cmdReqStockComp.ExecuteReader();
gvReportingStockComp.DataSource = readerReqStockComp;
gvReportingStockComp.DataBind();
oConnexion.Close();
oConnexion.Dispose();
如果我为了进行导出而添加下一个代码,它就可以工作了:
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=TestMES.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvReportingStockComp.RenderControl(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();
第一只手阻止:
gvReportingStockComp.RenderControl(hw);
和visual studio说:“必须使用runat = server声明GridView”
或阻止:
pdfDoc.Close();
他说:pdfDoc是空的......
有人有想法吗?
答案 0 :(得分:1)
添加以下代码以避免runat =“server”错误。
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
您可能希望禁用分页,以便将Gridview的所有行导出为PDF。
在gridview的rendercontrol方法之前添加以下代码。
gvReportingStockComp.AllowPaging = false;
gvReportingStockComp.DataBind();
如果您有任何疑问,请参阅下文。
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
答案 1 :(得分:0)
在PDF代码后添加Rendering
功能
public override void VerifyRenderingInServerForm(Control control)
{
// verifies the control is rendered here
}