Cấp bậc tác giả:

DOTNET

Xuất từ GridView sang Excel

Được viết bởi QuangIT ngày 31/05/2013 lúc 11:53 PM
Thực hiện các chức năng xuất. Sửa đổi mã cho chức năng ExportGridView như dưới đây.
  • 0
  • 7784

Xuất từ GridView sang Excel

Thực hiện các chức năng xuất.
Sửa đổi mã cho chức năng ExportGridView như dưới đây.

private void ExportGridView()
{
          string attachment = "attachment; filename=Contacts.xls";
          Response.ClearContent();
          Response.AddHeader("content-disposition", attachment);
          Response.ContentType = "application/ms-excel";
          StringWriter sw = new StringWriter();
          HtmlTextWriter htw = new HtmlTextWriter(sw);
 
          // Create a form to contain the grid
          HtmlForm frm = new HtmlForm();
          GridView1.Parent.Controls.Add(frm);
          frm.Attributes["runat"] = "server";
          frm.Controls.Add(GridView1);
 
          frm.RenderControl(htw);
          //GridView1.RenderControl(htw);
          Response.Write(sw.ToString());
          Response.End();
}

Sẽ gặp lỗi như hình bên dưới

exportexcell01.jpg

RegisterForEventValidation can only be called during Render();
lỗi dòng frm.RenderControl(htw);

Bạn cần sửa đổi 1 chút ở đầu trang như sau:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Records.aspx.cs" Inherits="Records" 
MasterPageFile="~/Master.master"  EnableEventValidation="false" %>

exportexcell02.jpg

Nguồn bài viết: DOTNET.VN

BÌNH LUẬN BÀI VIẾT

Bài viết mới nhất

LIKE BOX

Bài viết được xem nhiều nhất

HỌC HTML