2012-05-02 31 views
5

Tôi muốn lưu tệp excel xuất dữ liệu của chế độ xem lưới. Tôi đã viết mã để xuất dữ liệu GridView thành excel nhưng tôi không biết cách lưu tệp đã xuất.Xuất dạng xem lưới thành excel và lưu tệp excel vào thư mục

Tiếp theo là mã của tôi để xuất khẩu GridView vào excel:

Response.Clear(); 
Response.Buffer = true; 
Response.ContentType = "application/vnd.ms-excel"; 
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls"); 
Response.Charset = ""; 
this.EnableViewState = false; 
System.IO.StringWriter sw = new System.IO.StringWriter(); 
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 
gvFiles.RenderControl(htw); 
Response.Write(sw.ToString()); 
Response.End(); 
+5

Bạn biết rằng bạn không xuất khẩu excel tập tin nhưng một bảng html? Excel có thể giải thích nó, dù sao nó không phải là một tập tin excel thực sự. Hãy xem [EPPLus] (http://epplus.codeplex.com/releases/view/42439). –

+0

Giống như Tim nói sử dụng EPPlus - đó là thư viện sẽ tạo các tệp .xlsx thực tế cho bạn và sau đó bạn có thể tải xuống các tệp này. Tôi đã sử dụng nó cho một ứng dụng giám sát ngân sách và nó rực rỡ. – markp3rry

+0

DataSource cho chế độ xem lưới của bạn là gì? –

Trả lời

10

Bạn có thể làm điều này:

private void ExportGridView() 
{ 
    System.IO.StringWriter sw = new System.IO.StringWriter(); 
    System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw); 

    // Render grid view control. 
    gvFiles.RenderControl(htw); 

    // Write the rendered content to a file. 
    string renderedGridView = sw.ToString(); 
    System.IO.File.WriteAllText(@"C:\Path\On\Server\ExportedFile.xlsx", renderedGridView); 
} 
+1

cho tôi lỗi Điều khiển 'gvFiles' thuộc loại 'GridView' phải được đặt bên trong thẻ biểu mẫu với runat = server. :( – Neo

+1

nhận được ans public override void VerifyRenderingInServerForm (Control điều khiển) {} – Neo

0

Bạn đang hỏi làm thế nào để lưu các tập tin xuất khẩu ... Mã của bạn đặt nội dung trả lại của GridView (HTML) vào đáp ứng. Trong trường hợp này trình duyệt của bạn (phía máy khách) sẽ nhận được phản hồi này và bật lên một hộp thoại hỏi nơi lưu nó. Vì vậy, trình duyệt của bạn sẽ lưu tệp cho bạn.

Nếu bạn muốn lưu phía máy chủ, bạn không được đặt khung nhìn lưới được hiển thị vào phản hồi. Viết nó vào một tập tin trên đĩa cứng địa phương thay vào đó (như câu trả lời ở trên cho thấy). Hãy nhớ rằng, trong một môi trường khác với máy phát triển của riêng bạn (ví dụ: môi trường sản xuất), quy trình nhân viên ASP.NET có thể không có đủ quyền truy cập để ghi vào vị trí được chỉ định trên đĩa cứng. Dưới đây là một vài câu trả lời rằng adresses vấn đề rằng:

ASP.net user account permissions
ASP.NET + Access to the path is denied
System.UnauthorizedAccessException: Access to the path is denied

1

này có thể giúp bạn //

protected void exporttoexcel_Click(object sender, EventArgs e) 
{ 
    Response.Clear(); 

    Response.AddHeader("content-disposition", "attachment;filename=" attachment" + ".xls"); 

    Response.Charset = ""; 

    // If you want the option to open the Excel file without saving than 

    // comment out the line below 

    // Response.Cache.SetCacheability(HttpCacheability.NoCache); 

    Response.ContentType = "application/vnd.xls"; 

    System.IO.StringWriter stringWrite = new System.IO.StringWriter(); 

    System.Web.UI.HtmlTextWriter htmlWrite = 
    new HtmlTextWriter(stringWrite); 

    GridView1.RenderControl(htmlWrite); 

    Response.Write(stringWrite.ToString()); 

    Response.End(); 

} 
public override void VerifyRenderingInServerForm(Control control) 
{ 

    // Confirms that an HtmlForm control is rendered for the 
    //specified ASP.NET server control at run time. 

} 
+0

này đã giúp tôi làm việc trên mã hoàn chỉnh Export-To-Excel. am chỉ là không như vậy chắc chắn về việc giữ gìn 'VerifyRenderingInServerForm (Control điều khiển) 'mặc dù trống rỗng. – AceMark

0

Folowed liên kết: C# Excel file OLEDB read HTML IMPORT

Sử dụng Extended Properties=\"HTML Import;HDR=No;IMEX=1 the select * from [tablename], tablename được trả lại từ GetOleDbSchemaTable.

Lưu ý: Điều này sẽ không tải excel thông thường. Để sử dụng số Extended Properties=\"Excel 8.0;HDR=No;IMEX=1\, trong đó tên bảng sẽ có dấu hiệu $.

Kiểm tra mẫu mã: Can't read excel file after creating it using File.WriteAllText() function

1
public partial class exportgridtoexcel : System.Web.UI.Page 
{ 
    SqlConnection con=new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString.ToString()); 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!Page.IsPostBack) 
     { 
      GetData(); 
     } 
    } 
    public void GetData() 
    { 
     SqlDataAdapter sda = new SqlDataAdapter("select * from EmpData", con); 
     DataTable dt = new DataTable(); 
     sda.Fill(dt); 
     GridView1.DataSource = dt; 
     GridView1.DataBind(); 
    } 

    protected void btnDownload_Click(object sender, EventArgs e) 
    { 
     GetData(); 
     exporttoexcel("Report.xls", GridView1); 
     GridView1 = null; 
     GridView1.Dispose(); 



    } 
    public void exporttoexcel(string filename,GridView gv) 
    { 
     Response.ClearContent(); 
     Response.AddHeader("content-disposition", "attachment;filename=" + filename); 
     Response.ContentType = "applicatio/excel"; 
     StringWriter sw = new StringWriter(); ; 
     HtmlTextWriter htm=new HtmlTextWriter(sw); 
     gv.RenderControl(htm); 
     Response.Write(sw.ToString()); 
     Response.End(); 
    } 
    public override void VerifyRenderingInServerForm(Control control) 
    { 

    } 
} 

}

-1

trước tiên hãy thêm tham chiếu EPPLUS ence thư viện vào ứng dụng và thêm bằng cách sử dụng OfficeOpenXml;

// đối tượng kinh doanh lớp

bocls lớp {

string name; 

    public string NAME 
    { 
     get { return name; } 
     set { name = value; } 
    } 
    string id; 

    public string ID 
    { 
     get { return id; } 
     set { id = value; } 
    } 



    public bocls() { } 
    public bocls(string name, string id) 
    { 
     this.name = name; 
     this.id = id;   

    } 

// trong trường hợp xuất khẩu nút bấm

protected void lbtnExport_Click (object sender, EventArgs e) {

  List<bocls> list6 = new List<bocls>(); 
      //copy the grid view values into list 
      list6 = (from row in dataGridView1.Rows.Cast<DataGridViewRow>() 
      from cell in row.Cells.Cast<DataGridViewCell>() 
      select new 
      { 
       //project into your new class from the row and cell vars. 
      }).ToList(); 
    } 
      ExcelPackage excel = new ExcelPackage(); 
      var workSheet = excel.Workbook.Worksheets.Add("Products"); 
      var totalCols = GridView1.Rows[0].Cells.Count; 
      var totalRows = GridView1.Rows.Count; 
      var headerRow = GridView1.HeaderRow; 
      for (var i = 1; i <= totalCols; i++) 
      { 
       workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text; 
      } 
      for (var j = 1; j <= totalRows; j++) 
      { 
       for (var i = 1; i <= totalCols; i++) 
       { 
        var item = list6.ElementAt(j - 1); 

        workSheet.Column(1).Width = 13; 
        workSheet.Column(2).Width = 10; 

        workSheet.Cells[j + 1, i].Style.WrapText = true; 

        if (headerRow.Cells[i - 1].Text == "ID") 
         workSheet.Cells[j + 1, i].Value = item.GetType().GetProperty("id").GetValue(item, null); 
        else if (headerRow.Cells[i - 1].Text == "NAME") 
         workSheet.Cells[j + 1, i].Value = item.GetType().GetProperty("name").GetValue(item, null); 

        workSheet.Cells[j + 1, i].Value = workSheet.Cells[j + 1, i].Value.ToString().Replace("<br/>", ""); 
       } 
      } 
      using (var memoryStream = new MemoryStream()) 
      { 

       Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
       string filename = Guid.NewGuid().ToString() + ".xlsx"; 
       Response.AddHeader("content-disposition", "attachment; filename=" + filename); 
       excel.SaveAs(memoryStream); 
       //add your destination folder 
       FileStream fileStream = new FileStream(@"C:\Users\karthi\Downloads\New folder\" + filename, FileMode.Create,FileAccess.Write,FileShare.Write); 
       memoryStream.WriteTo(fileStream); 
       fileStream.Close(); 
       memoryStream.WriteTo(Response.OutputStream); 
       memoryStream.Close(); 
       memoryStream.WriteTo(Response.OutputStream); 
       Response.Flush(); 
       Response.End(); 
      } 

    } 
Các vấn đề liên quan