簡體   English   中英

如何在C#中將datagridview導出到Excel?

[英]How can I export a datagridview to a Excel in c#?, I have an error

下面是代碼:

private void ExportarDataGridViewExcel(DataGridView grd)
{
   SaveFileDialog fichero = new SaveFileDialog();
   fichero.Filter = "Excel (*.xls)|*.xls";
   if (fichero.ShowDialog() == DialogResult.OK)
   {
       Microsoft.Office.Interop.Excel.Application aplicacion;
       Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
       Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
       aplicacion = new Microsoft.Office.Interop.Excel.Application();
       libros_trabajo = aplicacion.Workbooks.Add();
       hoja_trabajo = (Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);

       for (int i = 0; i < grd.Rows.Count - 1; i++)
       {
           for (int j = 0; j < grd.Columns.Count; j++)
           {
               hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();
           }
       }
       libros_trabajo.SaveAs(fichero.FileName, 
           Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
       libros_trabajo.Close(true);
       aplicacion.Quit();
    }
}

它工作正常,幾乎沒有數據,但是當我使用更多數據時,該程序停止工作並說:

No se controló COMException
Excepción de HRESULT: 0x800AC472 

在這一部分:

for (int j = 0; j < grd.Columns.Count; j++)
{
   //PROBLEM// hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();//PROBLEM
}

請幫忙。

創建沒有母版頁集成的一頁(如果您在Asp.Net中使用母版頁)。

然后將“頁面加載事件”中的所有內容綁定到網格上所需的數據並將其添加

public void CerateExcel()
    {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("content-disposition", "attachment;filename=Name.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);

        form1.RenderControl(hw); //form1 it's name of you .aspx page (a form name with runat='server' tag)

        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM