2016-06-23 82 views
-1

沒有找到什麼好的解決辦法到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以實現所有這一切?我是否需要使用一些圖書館或其他工具,如報告查看器?有沒有可能?

+0

你可以分享你的研究,到目前爲止,即使以後的工作? –

回答

-1

找到解決方案

下載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; 
相關問題