2012-05-02 10 views
5

Desidero salvare il file excel che esporta i dati della visualizzazione griglia. Ho scritto codice per esportare i dati di gridview in Excel ma non so come salvare il file esportato.Esporta vista griglia per eccellere e salvare il file excel nella cartella

seguito è il mio codice per esportare GridView in 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

Sai che non stai esportando un file excel ma una tabella html? Excel può interpretarlo, comunque non è un vero file excel. Dai un'occhiata a [EPPLus] (http://epplus.codeplex.com/releases/view/42439). –

+0

Come Tim dice usare EPPlus - è una libreria che genererà file .xlsx per te e poi puoi scaricarli. L'ho usato per un'applicazione di monitoraggio del budget ed è geniale. – markp3rry

+0

qual è il DataSource per la vista della griglia? –

risposta

10

Si può fare questo:

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

assegnandomi l'errore Il controllo 'gvFiles' di tipo 'GridView' deve essere inserito all'interno di un tag form con runat = server. :( – Neo

+1

ottenuto l'ans di override public void VerifyRenderingInServerForm (controllo Control) {} – Neo

0

stai chiedendo come salvare il file esportato ... Il codice mette i contenuti resi del GridView (HTML) nella risposta. In questo caso il tuo browser (lato client) riceverà questa risposta e apparirà una finestra di dialogo in cui viene chiesto dove salvarla. Quindi il tuo browser salverà il file per te.

Se si desidera salvarlo lato server, non è necessario inserire la griglia visualizzata nella risposta. Scrivilo su un file sul disco fisso locale (come la risposta sopra mostra).

Ricordare che, in un ambiente diverso dal proprio computer di sviluppo (ad esempio un ambiente di produzione), il processo di lavoro ASP.NET potrebbe non disporre di sufficienti diritti di accesso per scrivere nella posizione specificata sul disco rigido. Qui ci sono un paio di risposte che adresses quel problema:

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

1

questo può aiutare //

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

questo mi ha aiutato a lavorare sul codice completo Export-to-Excel. sono solo, non così sicuro di mantenere 'VerifyRenderingInServerForm (Controllo di controllo) 'vuoto però. – AceMark

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

prima aggiungere EPPLUS consultare accedere alla libreria in un'applicazione e aggiungere utilizzando OfficeOpenXml;

// oggetto di business class

bocls classe {

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;   

    } 

// in caso pulsante di esportazione click

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(); 
      } 

    } 
Problemi correlati