其實這問題是發生在匯出Excel上面,加上這個方法就OK
public override void VerifyRenderingInServerForm(Control control)
{
}
然後...反正都寫了Excel就連PDF一起提供吧,點繼續閱讀有完整範例程式碼喔~
參考網址
前台程式碼,這次比較偷懶名字沒好好取..
<div>
<asp:button id="Button1" onclick="Button1_Click" runat="server" text="即時產生PDF">
<asp:button id="Button2" onclick="Button2_Click" runat="server" text="即時產生Excel">
<asp:gridview id="GridView1" runat="server">
</asp:gridview>
</div>
後台程式碼
public class member
{
private string _id;
private string _name;
public member(string ID, string Name)
{
_id = ID;
_name = Name;
}
public string ID
{
set { _id = value; }
get { return _id; }
}
public string Name
{
set { _name = value; }
get { return _name; }
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<member> mem = new List<member>();
mem.Add(new member("1", "Puma"));
mem.Add(new member("2", "F6 Team"));
this.GridView1.DataSource = mem;
this.GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
//匯出PDF
Response.ContentType = "application/pdf";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.AddHeader("content-disposition", "attachment;filename=test.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
System.IO.StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
form.Controls[0].RenderControl(htmlWrite);
StringReader reader = new StringReader(stringWrite.ToString());
Document doc = new Document(PageSize.A4);
HTMLWorker parser = new HTMLWorker(doc);
PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
parser.Parse(reader);
doc.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
//匯出Excel
Response.AddHeader("content-disposition", "attachment;filename=RetroCloud" + DateTime.Now.Ticks + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
string style = @"<style> .textmode { mso-number-format:\@; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
沒有留言:
張貼留言