.NET導出Gridview到excel 帶模板列顯示(未驗證)

http://blog.csdn.net/zouyujie1127/article/details/12002177


界面內容如下:

導出後顯示查詢到的數據如下:

c#調用代碼如下:

[csharp] view plain copy
 print?
  1. protected void btnOutput_Click(object sender, EventArgs e)  
  2.  {  
  3.      gvEquData.AllowPaging = false;  
  4.      BindGridViewData();  
  5.      ExcelHelper helper = new ExcelHelper();  
  6.      helper.ExportExcel(gvEquData, "設備狀態信息列表"+DateTime.Now.ToString("yyyyMMddHHmmss")+".xls""設備狀態信息列表");  
  7.  }  
這裏我使用了NPOI這個dll來操作excel,這個dll需要去網上下載。然後新建一個類用來操作excel,如下:
[csharp] view plain copy
 print?
  1. public class ExcelHelper  
  2. {  
  3.     #region  NPOI Excel導出  
  4.     /// <summary>  
  5.     /// 導出Excel   
  6.     /// </summary>  
  7.     /// <param name="GV">控件名稱(GridView) 如有需要稍加修改可應用於DateGird等.Net數據控件</param>  
  8.     /// <param name="ExcleName">保存的Excel名字</param>  
  9.     /// <param name="SheetName">工作簿名字</param>  
  10.     /// <param name="cols">圖片列 如果沒有圖片列 該參數可賦 NULL </param>  
  11.     public void ExportExcel(GridView GV, string ExcleName, string SheetName)  
  12.     {  
  13.         HSSFWorkbook hssfworkbook = new HSSFWorkbook();  
  14.         InitializeWorkbook(hssfworkbook, "雄帝"" Export  Excel ");  
  15.         HSSFSheet sheet1 = (HSSFSheet)hssfworkbook.CreateSheet(SheetName);  
  16.         HSSFPatriarch patriarch = (HSSFPatriarch)sheet1.CreateDrawingPatriarch();//插入圖片所用  
  17.         HSSFRow row;  
  18.         HSSFCell cell;  
  19.         //合併單元格信息  
  20.         int startRow = 0;  
  21.         int startColumn = 0;  
  22.         int span = 0;  
  23.         int col = 0;  
  24.         //當前的格數  
  25.         int rownum = 0;  
  26.   
  27.         row = (HSSFRow)sheet1.CreateRow(0);  
  28.         //添加Excel標題  
  29.         for (int K = 0; K < GV.HeaderRow.Cells.Count; K++)//GV.Columns.Count  
  30.         {  
  31.             cell = (HSSFCell)row.CreateCell(K);  
  32.             if (GV.HeaderRow.Cells[K].HasControls())  
  33.             {  
  34.                 ControlCollection cc=GV.HeaderRow.Cells[K].Controls;  
  35.                 if (cc.Count < 2)  
  36.                 {  
  37.                     if (cc[0] is Literal)  
  38.                     {  
  39.                         Literal ltl = cc[0] as Literal;  
  40.                         cell.SetCellValue(ltl.Text);  
  41.                     }  
  42.                     else  
  43.                     {  
  44.                         cell.SetCellValue(GV.Columns[K].HeaderText);  
  45.                     }  
  46.                 }  
  47.                 else  
  48.                 {  
  49.                     if (cc[1] is Literal)  
  50.                     {  
  51.                         Literal ltl = cc[1] as Literal;  
  52.                         cell.SetCellValue(ltl.Text);  
  53.                     }  
  54.                     else  
  55.                     {  
  56.                         cell.SetCellValue(GV.Columns[K].HeaderText);  
  57.                     }  
  58.                 }  
  59.             }  
  60.             else  
  61.             {  
  62.                 cell.SetCellValue(GV.Columns[K].HeaderText);//  
  63.             }  
  64.             //cell.SetCellValue(getCellText(GV.HeaderRow.Cells[K]));//  
  65.         }  
  66.         //加載數據  
  67.         for (int i = 0; i < GV.Rows.Count; i++)//  
  68.         {  
  69.             row = (HSSFRow)sheet1.CreateRow(i + 1);  
  70.             rownum = i + 1;  
  71.             for (int j = 0; j < GV.HeaderRow.Cells.Count; j++)//GV.Columns.Count  
  72.             {  
  73.                 if (GV.HeaderRow.Cells[j].Controls.Count>1)  
  74.                 {  
  75.                     cell = (HSSFCell)row.CreateCell(j);  
  76.                     if (GV.HeaderRow.Cells[j].Controls[0] is CheckBox)  
  77.                     {  
  78.                           
  79.                         CheckBox cbx = GV.HeaderRow.Cells[j].Controls[0] as CheckBox;  
  80.                         if (cbx.Checked)  
  81.                         {  
  82.                             cell.SetCellValue("是");  
  83.                         }  
  84.                         else  
  85.                         {  
  86.                             cell.SetCellValue("否");  
  87.                         }  
  88.                     }  
  89.                 }  
  90.                 else  
  91.                 {  
  92.                 TableCell Usecell = GV.Rows[i].Cells[j];  
  93.                 if (Usecell.RowSpan != 0 || Usecell.ColumnSpan != 0)//當含有和並列(行)的時候記錄該合併數據  
  94.                 {  
  95.                     startRow = i + 1;//起始行  
  96.                     startColumn = j;//起始列  
  97.                     span = Usecell.RowSpan;//合併的行數  
  98.                     col = Usecell.ColumnSpan;//合併的列數  
  99.                 }  
  100.                 cell = (HSSFCell)row.CreateCell(j);  
  101.                 //當處於合併狀時忽略該格式內容  
  102.                 if (i + 1 > startRow && j > startColumn && (startRow + span) > i + 1 && (startColumn + col) > j)  
  103.                 {  
  104.   
  105.                 }  
  106.                 else if (i + 1 == startRow && j == startColumn)  
  107.                 {  
  108.                     //進行單元格的合併  
  109.                     int row2 = (span == 0) ? 0 : (span - 1);  
  110.                     int col2 = (col == 0) ? 0 : (col - 1);  
  111.                     sheet1.AddMergedRegion(new Region(i + 1, j, i + row2 + 1, j + col2));  
  112.                     cell.SetCellValue(getCellText(GV.Rows[i].Cells[j]));  
  113.                 }  
  114.                 else  
  115.                 {  
  116.                     cell.SetCellValue(getCellText(GV.Rows[i].Cells[j]));  
  117.                 }  
  118.                 }  
  119.             }  
  120.         }  
  121.   
  122.         //加載Footer部分數據  
  123.         row = (HSSFRow)sheet1.CreateRow(rownum + 1);  
  124.   
  125.         int footerAt = 0;  
  126.         int footSpan = 0;  
  127.         if (GV.FooterRow != null)  
  128.         {  
  129.             for (int footNum = 0; footNum < GV.FooterRow.Cells.Count; footNum++)  
  130.             {  
  131.                 TableCell footTc = GV.FooterRow.Cells[footNum];  
  132.                 if (footTc.ColumnSpan != 0)  
  133.                 {  
  134.                     footSpan = footTc.ColumnSpan;  
  135.                     footerAt = footNum;  
  136.                 }  
  137.   
  138.                 cell = (HSSFCell)row.CreateCell(footNum);  
  139.   
  140.                 if (footNum > footerAt && footNum < footSpan + footerAt)  
  141.                 {  
  142.   
  143.                 }  
  144.                 else if (footNum == footerAt)//合併單元格  
  145.                 {  
  146.                     int footercol2 = (footSpan == 0) ? 0 : (footSpan - 1);  
  147.                     sheet1.AddMergedRegion(new Region(rownum + 1, footerAt, rownum + 1, footerAt + footercol2));  
  148.                     cell.SetCellValue(getCellText(GV.FooterRow.Cells[footNum]));  
  149.                 }  
  150.                 else  
  151.                 {  
  152.                     cell.SetCellValue(getCellText(footTc));  
  153.                 }  
  154.   
  155.             }  
  156.         }  
  157.         string path = ExcleName;  
  158.         ExportToExcel(hssfworkbook, ExcleName);  
  159.   
  160.     }  
  161.   
  162.     /// <summary>  
  163.     /// 導出Excel  
  164.     /// </summary>  
  165.     /// <param name="Dt">數據源</param>  
  166.     /// <param name="ExcleName">導入文件名稱</param>  
  167.     /// <param name="SheetName">工作薄名稱</param>  
  168.     /// <param name="titleArr">標題欄</param>  
  169.     /// <param name="clumnArr">欄位名</param>  
  170.     public void ExportExcel(DataTable Dt, string ExcleName, string SheetName, string[] titleArr, string[] clumnArr)  
  171.     {  
  172.         HSSFWorkbook hssfworkbook = new HSSFWorkbook();  
  173.         InitializeWorkbook(hssfworkbook, "雄帝"" Export  Excel ");  
  174.         HSSFSheet excelSheet = (HSSFSheet)hssfworkbook.CreateSheet(SheetName);  
  175.         int rowCount = 0;  
  176.         HSSFRow newRow = (HSSFRow)excelSheet.CreateRow(0);  
  177.         rowCount++;  
  178.         //循環寫出列頭           
  179.         for (int i = 0; i < titleArr.Length; i++)  
  180.         {  
  181.             HSSFCell newCell = (HSSFCell)newRow.CreateCell(i);  
  182.             newCell.SetCellValue(titleArr[i]);  
  183.         }  
  184.         for (int i = 0; i < Dt.Rows.Count; i++)  
  185.         {  
  186.             rowCount++;  
  187.             HSSFRow newRowData = (HSSFRow)excelSheet.CreateRow(rowCount);  
  188.             DataRow dr = Dt.Rows[i];  
  189.             for (int j = 0; j < clumnArr.Length; j++)  
  190.             {  
  191.                 HSSFCell newCell = (HSSFCell)newRow.CreateCell(rowCount);  
  192.                 newCell.SetCellValue(dr[titleArr[j]].ToString());  
  193.             }  
  194.         }  
  195.         string path = ExcleName;  
  196.         ExportToExcel(hssfworkbook, ExcleName);  
  197.     }  
  198.   
  199.     //獲取圖片路徑  
  200.     string getCellText(TableCell tc)  
  201.     {  
  202.         string result = HttpUtility.HtmlDecode(tc.Text);//HttpUtility.HtmlDecode(str);  
  203.         foreach (Control child in tc.Controls)  
  204.         {  
  205.             if (child is Label)  
  206.             {  
  207.                 result = HttpUtility.HtmlDecode(((Label)child).Text);  
  208.                 result = result.Trim();  
  209.                 break;  
  210.             }  
  211.         }  
  212.         string textLast = result.Trim();  
  213.         return textLast;  
  214.     }  
  215.   
  216.     /// <summary>  
  217.     /// 對產生的Excel進行文本輸入  
  218.     /// </summary>  
  219.     /// <param name="Path">輸出路徑</param>  
  220.     public void WriteToFile(string Path)  
  221.     {  
  222.         ////Write the stream data of workbook to the root directory  
  223.         //FileStream file = new FileStream(Path, FileMode.Create);  
  224.         //hssfworkbook.Write(file);  
  225.         //file.Close();  
  226.     }  
  227.   
  228.     /// <summary>  
  229.     /// 填寫Excel文本屬性  如有需要可以進行函數擴展 添加更多的屬性值  
  230.     /// </summary>  
  231.     /// <param name="CompanyName">公司名稱</param>  
  232.     /// <param name="Subject">文檔主題</param>  
  233.     public void InitializeWorkbook(HSSFWorkbook hssfworkbook, string CompanyName, string Subject)  
  234.     {  
  235.         //hssfworkbook = new HSSFWorkbook();  
  236.   
  237.         //create a entry of DocumentSummaryInformation  
  238.         DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
  239.         dsi.Company = CompanyName;  
  240.         hssfworkbook.DocumentSummaryInformation = dsi;  
  241.   
  242.         //create a entry of SummaryInformation  
  243.         SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
  244.         si.Subject = Subject;  
  245.         hssfworkbook.SummaryInformation = si;  
  246.     }  
  247.   
  248.     MemoryStream WriteToStream(HSSFWorkbook hssfworkbook)  
  249.     {  
  250.         //Write the stream data of workbook to the root directory  
  251.         MemoryStream file = new MemoryStream();  
  252.         hssfworkbook.Write(file);  
  253.         return file;  
  254.     }  
  255.   
  256.     public void ExportToExcel(HSSFWorkbook hssfworkbook, string filePath)  
  257.     {  
  258.         #region  //以字符流的形式下載文件  
  259.         //FileStream fs = new FileStream(Apppath + filePath, FileMode.Open);  
  260.         //byte[] bytes = new byte[(int)fs.Length];  
  261.         //fs.Read(bytes, 0, bytes.Length);  
  262.         //fs.Close();  
  263.         #endregion  
  264.   
  265.         HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";  
  266.         HttpContext.Current.Response.AddHeader("Content-Disposition""attachment; filename=" +   
  267. HttpUtility.UrlEncode(filePath, System.Text.Encoding.UTF8));  
  268.         HttpContext.Current.Response.Clear();  
  269.   
  270.         //HttpContext.Current.Response.BinaryWrite(bytes);  
  271.         HttpContext.Current.Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer());  
  272.         HttpContext.Current.Response.Flush();  
  273.         //HttpContext.Current.Response.End();  
  274.         //HttpContext.Current.Response.IsClientConnected  
  275.   
  276.     }  
  277.     #endregion  
  278. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章