将GridView导出到Excel,并将页面方向设置为景观



尚未找到任何出色的解决方案,可以将GridView导出到Excel,并具有以下选项:

  1. 页面方向设置为景观
  2. 边缘正常
  3. 所有列适合一个页面

现有导出到Excel的代码如下

private void ExportToExcel(GridView grdGridView)
    {
        DataTable dt = Whatever();             
        grdGridView.AllowPaging = false;
        grdGridView.Columns[13].Visible = false;
        grdGridView.DataSource = dt;
        grdGridView.DataBind();
        string attachment = "attachment; filename=ExcelSheet1.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);         
        HtmlForm frm = new HtmlForm();                        // Create a form to contain the grid
        grdGridView.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(grdGridView);
        frm.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
        }
}

为了实现这一切,如何出口到Excel的最佳方法是什么?我需要使用一些库或其他工具,例如报告查看器吗?是否可能?

找到解决方案

下载epplus库。

using OfficeOpenXml;
   private void ExportToExcel()
    {
        using (ExcelPackage objExcelPackage = new ExcelPackage())
        {
                //Create the worksheet    
                ExcelWorksheet objWorksheet = objExcelPackage.Workbook.Worksheets.Add("ExcelSheet1");
            DataTable dtQuoteComparison = dt   //Load the datatable into the sheet, starting from cell A1. Print the column names on row 1    
            objWorksheet.Cells["A1"].LoadFromDataTable(dt, true);

            var start = objWorksheet.Dimension.Start;
            var end = objWorksheet.Dimension.End;
            for (int row = start.Row+1; row <= end.Row; row++) //iterate through rows
            {                    
               objWorksheet.Cells[rowStart, colStart, rowEnd,colEnd].WhateverProperty=value; 
            }
            objWorksheet.PrinterSettings.Orientation = eOrientation.Landscape;
            objWorksheet.PrinterSettings.FitToWidth = 1;
            //Write it back to the client    
            if (System.IO.File.Exists(filepath))
                System.IO.File.Delete(filepath);
            //Create excel file on physical disk    
            FileStream objFileStrm = System.IO.File.Create(filepath);
            objFileStrm.Close();
            //Write content to excel file    
            System.IO.File.WriteAllBytes(filepath,objExcelPackage.GetAsByteArray());
        }
    }

现在我面临的问题是,即使在设置之后,所有适合一个页面都无法正常工作

 objWorksheet.PrinterSettings.FitToWidth = 1;

最新更新