接合grid,直接读数据库后输出到Execl-
- public static void OutExecl(string FileName, string mSQL, FineUI.Grid grid)//数据导出到Execl
- {
- string SQL = mSQL, SQL1 = "", SQL2 = "", SQL3 = "";
- int n = 0;
- n = mSQL.IndexOf(" top ");
- if (n >= 0)//去掉Top nnn
- {
- SQL1 = SQL.Substring(0,n);
- SQL2 = SQL.Substring(n+5).TrimStart();//, mSQL.Length - n - 6
- n = SQL2.IndexOf(" ");
- SQL3 = SQL2.Substring(n + 1);// ,SQL2.Length - n
- SQL = SQL1 +" "+ SQL3;
- }
- DataSet ds =new DataSet();
- fun.CreateExcelForHtml(ds, FileName + "_Html.xls", grid);//将DataSet中的数据导出Execl,CSV格式
- ds.Clear();
- ds.Dispose();
- }
- public static string ReturnCaption(string FieldName, FineUI.Grid grid)//根据字段名返回中文名称
- {
- string temp,F=FieldName.ToLower();
- foreach (GridColumn column in grid.Columns)
- {
- temp=column.HeaderText;
- if (F == column.SortField.ToLower()) return temp;//SortField必需赋值
- }
- return FieldName;
- }
- public static void CreateExcelForHtml(DataSet ds, string FileName, FineUI.Grid grid)//将DataSet中的数据导出Execl For Html 格式
- {
- HttpResponse resp;
- resp = HttpContext.Current.Response;//HttpContext.Current.
- resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
- resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
- resp.ContentType = "application/excel";
- string colHeaders = "", ls_item = "",F,C;
- StringBuilder sb = new StringBuilder();
- sb.Append("<table cellspacing="0" rules="all" border="1" style="border-collapse:collapse;">");
- sb.Append("<tr>");
- DataTable dt = ds.Tables[0];//定义表对象与行对象,同时用DataSet对其值进行初始化
- DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
- int i = 0;
- int cl = dt.Columns.Count;
- for (i = 0; i < cl; i++)//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
- {
- colHeaders = dt.Columns[i].Caption.ToString();
- colHeaders = ReturnCaption(colHeaders, grid);//根据字段名返回中文名称
- sb.AppendFormat("<td>{0}</td>", colHeaders);
- }
- sb.Append("</tr>");
- for (i = 0; i < cl; i++)//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
- {
- colHeaders = dt.Columns[i].Caption.ToString();
- //colHeaders = ReturnCaption(colHeaders, grid);//根据字段名返回中文名称
- sb.AppendFormat("<td>{0}</td>", colHeaders);
- }
- sb.Append("</tr>");
- foreach (DataRow row in myRow)//逐行处理数据
- {
- sb.Append("<tr>");
- for (i = 0; i < cl; i++)//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
- {
- ls_item = row[i].ToString().Trim();
- F = dt.Columns[i].Caption.ToString().ToLower();
- C = ReturnCaption(F, grid);//根据字段名返回中文名称
- if (F == "cardnumber" || F == "autoid" || F == "nodenumber" || F == "parentnodenumber"||C.IndexOf("号")>=0)
- {
- sb.AppendFormat("<td style='mso-number-format:"\\@";'>{0}</td>", ls_item);
- }
- else sb.AppendFormat("<td>{0}</td>", ls_item);
- }
- sb.Append("</tr>");
- }
- sb.Append("</table>");
- resp.Write(sb.ToString());//向HTTP输出流中写入取得的数据信息
- resp.End();
- }
复制代码 |