关于Gridview中使用控件和图片导出到Excel的处理

首先是大家在网上能搜索一箩筐的仅导出数据的做法:
  1. public static void Export(Page pg, GridView gv,bool alowPage, string FileName)  
  2.         {  
  3.             pg.Response.Clear();  
  4.             pg.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");  
  5.             pg.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());  
  6.             pg.Response.ContentEncoding = System.Text.Encoding.UTF8;  
  7.             pg.Response.ContentType = "application/vnd.ms-excel";//设置输出文件类型为excel文件。    
  8.             pg.Response.Charset = "";  
  9.   
  10.             System.IO.StringWriter oStringWriter = new System.IO.StringWriter();  
  11.             System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);  
  12.             if (!alowPage)  
  13.   
  14.            {  
  15.   
  16.                   gv.AllowPaging = false;  
  17.                   gv.DataBind();  
  18.   
  19.             }  
  20.             gv.RenderControl(oHtmlTextWriter);                  
  21.             pg.Response.Output.Write(oStringWriter.ToString());  
  22.             pg.Response.End();  
  23.   
  24.             if (!alowPage)  
  25.             {  
  26.                 gv.AllowPaging = true;  
  27.             }  
  28.         }   

 

这个可以处理导出当前页或导出所有数据。但是如果Gridview中包含图片列则就没有用了。经过网上查阅资料自己做了一个可以导出图片的方法,code如下:(以下代码仅供参考,有更好方法的共享下。)

  1. public static Excel.Application app;  
  2.         public static Excel.Worksheet workSheet;  
  3.         public static Excel.Workbook workBook;  
  4.         public static string fileName = string.Empty;  
  5.   
  6.         //单元格列号数组   
  7.         private static string[] colString = new string[26] { "A""B""C""D""E""F""G""H""I""J""K""L""M""N""O""P""Q""R""S""T""U""V""W""X""Y""Z" };  
  8.   
  9.         /// <summary>   
  10.         /// 将GridView数据写入Excel文件(自动分页)   
  11.         /// </summary>   
  12.         /// <param name="pag">Page</param>   
  13.         /// <param name="gv">GridView</param>   
  14.         /// <param name="rows">每个WorkSheet写入多少行数据</param>   
  15.         /// <param name="top">表格数据起始行索引</param>   
  16.         /// <param name="left">表格数据起始列索引</param>   
  17.         /// <param name="coluwidth">每列数据的宽度</param>   
  18.         public static void DataTableToExcel(Page pag, GridView gv, int rows, int top, int left,int[] coluwidth)  
  19.         {  
  20.             app = new Excel.Application();  
  21.             app.Visible = false;  
  22.             app.DisplayAlerts = false;  
  23.             workBook = app.Workbooks.Add(Type.Missing);  
  24.             int rowCount = gv.Rows.Count;  //DataTable行数   
  25.             int colCount = gv.Columns.Count; //DataTable列数   
  26.             int sheetCount = GetSheetCount(rowCount, rows); //WorkSheet个数   
  27.   
  28.             //复制sheetCount-1个WorkSheet对象   
  29.             for (int i = 1; i < sheetCount; i++)  
  30.             {  
  31.                 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);  
  32.                 workSheet.Copy(Missing.Value, workBook.Worksheets[i]);  
  33.             }  
  34.   
  35.             for (int i = 1; i <= sheetCount; i++)  
  36.             {  
  37.                 int startRow = (i - 1) * rows;  //记录起始行索引   
  38.                 int endRow = i * rows;   //记录结束行索引   
  39.   
  40.                 //若是最后一个WorkSheet,那么记录结束行索引为源DataTable行数   
  41.                 if (i == sheetCount)  
  42.                     endRow = rowCount;  
  43.   
  44.                 //获取要写入数据的WorkSheet对象,并重命名   
  45.                 workSheet = (Excel.Worksheet)workBook.Worksheets.get_Item(i);  
  46.                 workSheet.Name = "页-" + i.ToString();  
  47.   
  48.                 GridViewRow headrow = gv.HeaderRow;  
  49.                 for (int h = 0; h < colCount; h++)//导出Gridview头部   
  50.                 {  
  51.                     Excel.Range range1 = GetRang(h + 1, 0);  
  52.                     range1.Font.Bold = 1;  
  53.                     range1.Value2 = headrow.Cells[h].Text;  
  54.                 }  
  55.   
  56.                 //将gv中的数据写入WorkSheet   
  57.                 for (int j = 1; j <= endRow - startRow; j++)  
  58.                 {  
  59.                     if (rowCount < j)  
  60.                         break;  
  61.                     for (int k = 0; k < colCount; k++)  
  62.                     {  
  63.                         if (gv.Rows[startRow + j - 1].Cells[k].HasControls())  
  64.                         {  
  65.                             Hashtable ht = GetControlNameAndType(gv, startRow + j - 1, k);  
  66.                             if (ht.Count > 0)  
  67.                             {  
  68.                                 string value = string.Empty;  
  69.                                 bool isImg = false;  
  70.                                 foreach (DictionaryEntry de in ht)  
  71.                                 {   
  72.                                     string []temp = de.Value.ToString().Split(',');  
  73.                                     if (temp[0] == "Image")  
  74.                                     {  
  75.                                         isImg = true;  
  76.                                         if (!AddImage(pag, temp[1], temp[2])) workSheet.Cells[top + j, left + k] = "未知图片";  
  77.                                     }  
  78.                                     else  
  79.                                     {  
  80.                                         isImg = false;  
  81.                                         value += temp[1]+"  ";  
  82.                                     }                                      
  83.                                 }  
  84.                                 if(!isImg)  
  85.                                     workSheet.Cells[top + j, left + k] = value;  
  86.                             }  
  87.                         }  
  88.                         else  
  89.                             workSheet.Cells[top + j, left + k] = gv.Rows[startRow + j - 1].Cells[k].Text;  
  90.                     }  
  91.                 }  
  92.   
  93.                 if (gv.ShowFooter == true)//导出Gridview的footer   
  94.                 {  
  95.                     GridViewRow footrow = gv.FooterRow;  
  96.                     for (int h = 0; h < colCount; h++)  
  97.                     {  
  98.                         Excel.Range range1 = GetRang(h + 1, gv.Rows.Count + 1);  
  99.                         range1.Font.Bold = 1;  
  100.                         if (footrow.Cells[h].Text != null && footrow.Cells[h].Text != " ")  
  101.                             range1.Value2 = footrow.Cells[h].Text;  
  102.                     }  
  103.                 }  
  104.                 SetColumnStyle(gv.Columns.Count, gv.Rows.Count, workSheet, coluwidth);//设置样式   
  105.             }  
  106.   
  107.             bool result = true;  
  108.             string realSavePath = SaveFile(pag, out result);  
  109.             if (realSavePath != "" && result)  
  110.             {  
  111.                 Export(pag,realSavePath);  
  112.             }  
  113.             else  
  114.                 pag.Response.Write("<mce:script type="text/javascript"><!--  
  115. alert('导出失败!//n错误原因:" + realSavePath.Replace("//", "") + "');  
  116. // --></mce:script>");   
  117.         }  
  118.   
  119.         //为用户提供导出的Excel文件的下载   
  120.         private static void Export(Page pg,string path)  
  121.         {  
  122.             FileInfo file = new FileInfo(path);  
  123.             if (file.Exists)  
  124.             {  
  125.                 pg.Response.Clear();  
  126.                 pg.Response.ClearHeaders();  
  127.                 pg.Response.Buffer = true;  
  128.                 pg.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-7");  
  129.                 pg.Response.AppendHeader("Content-Disposition""attachment;filename=" + HttpUtility.UrlEncode(path.Substring(path.LastIndexOf("//") + 1), Encoding.UTF8).ToString());  
  130.                 pg.Response.ContentEncoding = System.Text.Encoding.UTF7;  
  131.                 pg.Response.ContentType = "application/octet-stream";//设置输出文件类型为excel文件。    
  132.                 pg.Response.Charset = "";  
  133.                 pg.Response.WriteFile(file.FullName);  
  134.                 pg.Response.Flush();  
  135.                 file.Delete();//下载完成后删除文件   
  136.                 pg.Response.Write("<mce:script type="text/javascript"><!--  
  137. window.close();  
  138. // --></mce:script>");//自动关闭下载浏览器,防止用户手动关闭中断下载进程引起的文件没有删除   
  139.                 pg.Response.End();                  
  140.             }  
  141.             else  
  142.                 pg.Response.Write("<mce:script type="text/javascript"><!--  
  143. alert('导出失败!//n错误原因:" + path.Replace("//", "") + "');  
  144. // --></mce:script>");   
  145.         }  
  146.   
  147.         //制作缩微图并导出图片到Excel   
  148.         public static bool AddImage(Page pag,string url,string rangeName)  
  149.         {  
  150.             bool findImage = false;  
  151.             string path = pag.Server.MapPath(url);  
  152.             System.IO.FileInfo file = new System.IO.FileInfo(path);  
  153.             if (file.Exists)  
  154.             {  
  155.                 string savapath = "C://WINDOWS//Temp" + path.Substring(path.LastIndexOf("//"));  
  156.                 System.IO.FileInfo file2 = new System.IO.FileInfo(savapath);  
  157.                 if (file2.Exists)  
  158.                     file2.Delete();  
  159.                 ReturnValue val = ADOnline.Common.CommonImage.CreateAndSaveSmallImage(path, 80, 50, savapath);  
  160.                 if (val == ReturnValue.SUCCEED)  
  161.                 {  
  162.                     InsertPicture(rangeName, savapath, 80, 50);  
  163.                     findImage = true;  
  164.                 }  
  165.             }  
  166.             return findImage;  
  167.         }  
  168.   
  169.         //获取Gridview每列中的所有显示控件名称、类型和值   
  170.         public static Hashtable GetControlNameAndType(GridView gv,int row,int cell)  
  171.         {   
  172.             Hashtable ht = new Hashtable();  
  173.             if (gv.Rows[row].Cells[cell].Controls.Count > 0)  
  174.             {  
  175.                 for (int i = 0; i < gv.Rows[row].Cells[cell].Controls.Count; i++)  
  176.                 {  
  177.                     Control temp = gv.Rows[row].Cells[cell].Controls[i];  
  178.                     if (temp.GetType() == typeof(Label) && temp.Visible==true)  
  179.                         ht.Add(temp.ID, "Lable," + (temp as Label).Text + "," + colString[cell] + Convert.ToString(row + 2));  
  180.                     else if (temp.GetType() == typeof(DropDownList) && temp.Visible != false)  
  181.                         ht.Add(temp.ID, "DropDownList," + (temp as DropDownList).SelectedItem.Text + "," + colString[cell]+Convert.ToString(row+2));  
  182.                     else if (temp.GetType() == typeof(LinkButton) && temp.Visible != false)  
  183.                         ht.Add(temp.ID, "LinkButton," + (temp as LinkButton).Text + "," + colString[cell] + Convert.ToString(row + 2));  
  184.                     else if (temp.GetType() == typeof(CheckBox) && temp.Visible != false)  
  185.                         ht.Add(temp.ID, "CheckBox," + ((temp as CheckBox).Checked==true ? "true" : "false") + "," + colString[cell] + Convert.ToString(row + 2));  
  186.                     else if (temp.GetType() == typeof(Image) && temp.Visible != false)  
  187.                         ht.Add(temp.ID, "Image," + (temp as Image).ImageUrl + "," + colString[cell] + Convert.ToString(row + 2));  
  188.                 }  
  189.             }  
  190.             return ht;  
  191.         }  
  192.   
  193.         //设置格式   
  194.         public static void SetColumnStyle(int colCount, int row, Excel.Worksheet ws, int[] coluwidth)  
  195.         {  
  196.             for (int i = 1; i <= colCount; i++)  
  197.             {  
  198.                 Excel.Range ran = ws.get_Range(ws.Cells[1, i], ws.Cells[row + 2, i]);  
  199.                 //ran.Select();   
  200.                 ran.WrapText = true;  
  201.                 ran.ColumnWidth = Convert.ToString(coluwidth[i - 1]);  
  202.                   
  203.                 ran.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;  
  204.                 ran.Borders.LineStyle = 1;  
  205.                 if (i == 3)  
  206.                     ran.RowHeight = Convert.ToString(51);  
  207.             }  
  208.         }  
  209.   
  210.   
  211.         //插入图片到Excel   
  212.         public static void InsertPicture(string RangeName, string PicturePath, float PictuteWidth, float PictureHeight)  
  213.         {  
  214.             Excel.Range rangeTemp = workSheet.get_Range(RangeName, Missing.Value);  
  215.             rangeTemp.Select();  
  216.             float PicLeft, PicTop;  
  217.             PicLeft = Convert.ToSingle(rangeTemp.Left)+2;  
  218.             PicTop = Convert.ToSingle(rangeTemp.Top) + 1;  
  219.             rangeTemp.ColumnWidth = Convert.ToString(15);  
  220.             rangeTemp.RowHeight = Convert.ToString(51);  
  221.             workSheet.Shapes.AddPicture(PicturePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, PicLeft, PicTop, 87, 50);  
  222.         }  
  223.   
  224.         /// <summary>   
  225.         /// 计算WorkSheet数量   
  226.         /// </summary>   
  227.         /// <param name="rowCount">记录总行数</param>   
  228.         /// <param name="rows">每WorkSheet行数</param>   
  229.         public static int GetSheetCount(int rowCount, int rows)  
  230.         {  
  231.             int n = rowCount % rows;  //余数   
  232.   
  233.             if (n == 0)  
  234.                 return rowCount / rows;  
  235.             else  
  236.                 return Convert.ToInt32(rowCount / rows) + 1;  
  237.         }  
  238.   
  239.         //获取指定单元格   
  240.         public static Excel.Range GetRang(int curColum, int rowNum)  
  241.         {  
  242.             if (curColum < 0 || curColum > 255)  
  243.                 throw new Exception("列号出错!");  
  244.             string rangName = string.Empty;  
  245.             if (curColum <= 26)  
  246.                 rangName = colString[curColum - 1] + Convert.ToString(rowNum+1);  
  247.             else  
  248.             {  
  249.                 int colNum = curColum / 26;  
  250.                 int temp = curColum % 26;  
  251.                 if (temp == 0)  
  252.                     rangName = colString[colNum - 1] + colString[25] + Convert.ToString(rowNum + 1);  
  253.                 else  
  254.                     rangName = colString[colNum] + colString[temp - 1] + Convert.ToString(rowNum + 1);  
  255.             }  
  256.             return workSheet.get_Range(rangName, System.Reflection.Missing.Value);   
  257.         }  
  258.   
  259.         /// <summary>   
  260.         /// 保存文件   
  261.         /// </summary>   
  262.         public static string SaveFile(Page pag,out bool result)  
  263.         {  
  264.             string defaultPath = pag.Server.MapPath("~/Record/ExcelReportTempFolder/") + GetFileName();  
  265.             result = true;  
  266.   
  267.             try  
  268.             {  
  269.                 workBook.SaveAs(defaultPath, Missing.Value, Missing.Value,  
  270.                   Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange,  
  271.                   Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);  
  272.             }  
  273.             catch (Exception ex)  
  274.             {  
  275.                 result = false;  
  276.                 defaultPath = ex.ToString();  
  277.             }  
  278.   
  279.             Close();  
  280.             Dispose();  
  281.             return defaultPath;  
  282.         }  
  283.   
  284.         //获取文件名称   
  285.         private static string GetFileName()  
  286.         {  
  287.             if (fileName == null || fileName.Trim() == "")  
  288.                 return (DateTime.Now.ToString().Replace(':''-') + "_report.xls");  
  289.             else if (fileName.LastIndexOf('.') == -1)  
  290.                 return fileName + ".xls";  
  291.             else if (fileName.Substring(fileName.LastIndexOf('.')) != ".xls")  
  292.                 return fileName.Substring(0, fileName.LastIndexOf('.')) + ".xls";  
  293.             else  
  294.                 return fileName;  
  295.         }  
  296.   
  297.         /// <summary>   
  298.         /// 关闭应用程序   
  299.         /// </summary>   
  300.         private static void Close()  
  301.         {  
  302.             workBook.Close(false, Missing.Value, Missing.Value);  
  303.             app.Quit();  
  304.         }  
  305.   
  306.         /// <summary>   
  307.         /// 释放所引用的COM对象。   
  308.         /// </summary>   
  309.         public static void Dispose()  
  310.         {  
  311.             ReleaseObj(workSheet);  
  312.             ReleaseObj(workBook);  
  313.             ReleaseObj(app);  
  314.             app = null;  
  315.             System.GC.Collect();  
  316.             System.GC.WaitForPendingFinalizers();  
  317.         }  
  318.   
  319.         /// <summary>   
  320.         /// 释放对象,内部调用   
  321.         /// </summary>   
  322.         /// <param name="o"></param>   
  323.         private static void ReleaseObj(object o)  
  324.         {  
  325.             try  
  326.             {  
  327.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(o);  
  328.             }  
  329.             catch { }  
  330.             finally { o = null; }  
  331.         }  

该方法提供了获取单元格、设置格式、判断Gridview中的数据、分页、保存零时文件并下载等功能。仅为一个测试代码。可以根据自己的需求来完善。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值