通过添加所有选定的列将GridView导出到Excel

时间:2018-12-11 06:23:25

标签: missing-data

我在这里使用GridView显示数据。为了将Gridview数据导出为ex​​cel格式,我使用了一个按钮-“下载到Excel”。下载到Excel格式或导出到Excel可以正常工作。该GridView显示总共15列。  我的问题是我想显示Excel工作表中的所有列。但是我的最后第二列在下载的excel中丢失了。 以下是我的代码

public void ExportData(DataTable oGrid, string exportFile)
    {
        try
        {
            Response.ClearContent();
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "TripAssignVsTripAcceptanceVsTripPlacedReport"));
            HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
            HttpContext.Current.Response.AddHeader("Pragma", "public");
            // oGrid.AllowPaging = false;
           // oGrid.DataBind();
            StringBuilder strbldr = new StringBuilder();
            for (int i = 0; i < oGrid.Columns.Count; i++)
            {
                //separting header columns text with comma operator
                strbldr.Append(oGrid.Columns[i].ColumnName + ',');
            }
            //appending new line for gridview header row
            strbldr.Append("\n");
            for (int j = 0; j < oGrid.Rows.Count; j++)
            {

                for (int k = 0; k < oGrid.Columns.Count; k++)
                {
                    //separating gridview columns with comma

                    //strbldr.Append(oGrid.Rows[j].Cells[k].ToString() + ',');

                    strbldr.Append(oGrid.Rows[j].ItemArray[k].ToString().Replace(",", "").ToString() + ',');
                }
                //appending new line for gridview rows
                strbldr.Append("\n");
            }
            Response.Write(strbldr.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }

public void ExportDataSetToExcel(DataSet ds, string filename)
    {
        HttpResponse response = HttpContext.Current.Response;

        // first let's clean up the response.object   
        response.Clear();
        response.Charset = "";

        // set the response mime type for excel   
        response.ContentType = "application/vnd.ms-excel";

        response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

        // create a string writer   

        using (StringWriter sw = new StringWriter())
        {

            using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {

                // instantiate a datagrid   
                DataGrid dg = new DataGrid();
                dg.DataSource = ds.Tables[0];

                dg.DataBind();
                dg.RenderControl(htw);


                response.Write(sw.ToString());

                response.End();
            }
        }
    }

}

0 个答案:

没有答案