using System; using System.Collections.Generic; using System.Text; using System.Data; using System.IO; using System.Web; using Microsoft.Office.Interop.Excel; using System.Reflection;

/*  * 开发人员:Hisen  * 时间:2008年11月24日  * 功能:将数据导出Excel  *  */ namespace XT.LiTree.Logic {     public class ExcelExport     {         private ExcelExport()         { }         private static ExcelExport _instance = null;

public static ExcelExport Instance         {             get             {                 if (_instance == null) _instance = new ExcelExport();                 return _instance;             }         }

/// <summary>         /// DataTable直接导出Excel,此方法会把DataTable的数据用Excel打开,再自己手动去保存到确切的位置         /// </summary>         /// <param name="dt">要导出Excel的DataTable</param>         /// <returns></returns>         public bool DoExport(DataTable dt)         {             Application app = new ApplicationClass();             if (app == null)             {                 throw new Exception("Excel无法启动");             }             app.Visible = true;             Workbooks wbs = app.Workbooks;             Workbook wb = wbs.Add(Missing.Value);             Worksheet ws = (Worksheet)wb.Worksheets[1];

int cnt = dt.Rows.Count;             int columncnt = dt.Columns.Count;

// *****************获取数据********************             object[,] objData = new Object[cnt + 1, columncnt];  // 创建缓存数据             // 获取列标题             for (int i = 0; i < columncnt; i++)             {                 objData[0, i] = dt.Columns[i].ColumnName;             }             // 获取具体数据             for (int i = 0; i < cnt; i++)             {                 System.Data.DataRow dr = dt.Rows[i];                 for (int j = 0; j < columncnt; j++)                 {                     objData[i + 1, j] = dr[j];                 }             }

//********************* 写入Excel******************             Range r = ws.get_Range(app.Cells[1, 1], app.Cells[cnt + 1, columncnt]);             r.NumberFormat = "@";             //r = r.get_Resize(cnt+1, columncnt);             r.Value2 = objData;             r.EntireColumn.AutoFit();

app = null;             return true;         }

/// <summary>         /// DataTable通过流导出Excel         /// </summary>         /// <param name="ds">数据源DataSet</param>         /// <param name="columns">DataTable中列对应的列名(可以是中文),若为null则取DataTable中的字段名</param>         /// <param name="fileName">保存文件名(例如:a.xls)</param>         /// <returns></returns>         public bool StreamExport(DataTable dt, string[] columns, string fileName, System.Web.UI.Page pages)         {             if (dt.Rows.Count > 65535) //总行数大于Excel的行数             {                 throw new Exception("预导出的数据总行数大于excel的行数");             }             if (string.IsNullOrEmpty(fileName)) return false;                         StringBuilder content = new StringBuilder();             StringBuilder strtitle = new StringBuilder();             content.Append("<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>");             content.Append("<head><title></title><meta http-equiv='Content-Type' content=\"text/html; charset=gb2312\">");             //注意:[if gte mso 9]到[endif]之间的代码,用于显示Excel的网格线,若不想显示Excel的网格线,可以去掉此代码             content.Append("<!--[if gte mso 9]>");             content.Append("<xml>");             content.Append(" <x:ExcelWorkbook>");             content.Append("  <x:ExcelWorksheets>");             content.Append("   <x:ExcelWorksheet>");             content.Append("    <x:Name>Sheet1</x:Name>");             content.Append("    <x:WorksheetOptions>");             content.Append("      <x:Print>");             content.Append("       <x:ValidPrinterInfo />");             content.Append("      </x:Print>");             content.Append("    </x:WorksheetOptions>");             content.Append("   </x:ExcelWorksheet>");             content.Append("  </x:ExcelWorksheets>");             content.Append("</x:ExcelWorkbook>");             content.Append("</xml>");             content.Append("<![endif]-->");             content.Append("</head><body><table style='border-collapse:collapse;table-layout:fixed;'><tr>");

if (columns != null)             {                 for (int i = 0; i < columns.Length; i++)                 {                     if (columns[i] != null && columns[i] != "")                     {                         content.Append("<td><b>" + columns[i] + "</b></td>");                     }                     else                     {                         content.Append("<td><b>" + dt.Columns[i].ColumnName + "</b></td>");                     }                 }             }             else             {                 for (int j = 0; j < dt.Columns.Count; j++)                 {                     content.Append("<td><b>" + dt.Columns[j].ColumnName + "</b></td>");                 }             }             content.Append("</tr>\n");

for (int j = 0; j < dt.Rows.Count; j++)             {                 content.Append("<tr>");                 for (int k = 0; k < dt.Columns.Count; k++)                 {                     object obj = dt.Rows[j][k];                     Type type = obj.GetType();                     if (type.Name == "Int32" || type.Name == "Single" || type.Name == "Double" || type.Name == "Decimal")                     {                         double d = obj == DBNull.Value ? 0.0d : Convert.ToDouble(obj);                         if (type.Name == "Int32" || (d - Math.Truncate(d) == 0))                             content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0'>{0}</td>", obj);                         else                             content.AppendFormat("<td style='vnd.ms-excel.numberformat:#,##0.00'>{0}</td>", obj);                     }                     else                         content.AppendFormat("<td style='vnd.ms-excel.numberformat:@'>{0}</td>", obj);                 }                 content.Append("</tr>\n");             }             content.Append("</table></body></html>");             content.Replace("&nbsp;", "");             pages.Response.Clear();             pages.Response.Buffer = true;             pages.Response.ContentType = "application/ms-excel";  //"application/ms-excel";             pages.Response.Charset = "UTF-8";             pages.Response.ContentEncoding = System.Text.Encoding.UTF7;             fileName = System.Web.HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);             pages.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);             pages.Response.Write(content.ToString());             //pages.Response.End();  //注意,若使用此代码结束响应可能会出现“由于代码已经过优化或者本机框架位于调用堆栈之上,无法计算表达式的值。”的异常。             HttpContext.Current.ApplicationInstance.CompleteRequest(); //用此行代码代替上一行代码,则不会出现上面所说的异常。             return true;         }

/// <summary>         /// 直接由GridView导出Excel         /// </summary>         /// <param name="ctl">控件(一般是GridView)</param>         /// <param name="FileName">导出的文件名</param>         /// <param name="removeIndexs">要移除的列的索引数组(因为有时我们并不希望把GridView中的所有列全部导出)</param>         /// <param name="pages"></param>         public void ControlToExcel(System.Web.UI.WebControls.GridView ctl, string FileName, string[] removeIndexs, System.Web.UI.Page pages)         {             if (removeIndexs != null)             {                 foreach (string index in removeIndexs)                 {                     ctl.Columns[int.Parse(index)].Visible = false;                 }             }             pages.Response.Charset = "UTF-8";             pages.Response.ContentEncoding = System.Text.Encoding.UTF7;             pages.Response.ContentType = "application/ms-excel";             FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8);             pages.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);             ctl.Page.EnableViewState = false;             System.IO.StringWriter tw = new System.IO.StringWriter();             System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);             ctl.RenderControl(hw);             pages.Response.Write(tw.ToString());             HttpContext.Current.ApplicationInstance.CompleteRequest();         }     } }

C#导出EXCEL(DataTable导出EXCEL)的更多相关文章

  1. NPOI json转Excel DataTable转Excel ,Excel转DataTable

    JsonToExcel: public static void JsonToExcel(List<Dictionary<string, object>> json, strin ...

  2. asp.net DataTable导出Excel 自定义列名

    1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...

  3. DataTable导出到Excel

    简单的导出到Excel中: 代码如下: using System; using System.Collections.Generic; using System.Data; using System. ...

  4. DataTable 更改在有数据列的类型方法+DataTable 导出excel功能

    /// <summary> /// 导出功能 /// </summary> /// <param name="sender"></para ...

  5. [转].net 使用NPOI或MyXls把DataTable导出到Excel

    本文转自:http://www.cnblogs.com/yongfa365/archive/2010/05/10/NPOI-MyXls-DataTable-To-Excel-From-Excel.ht ...

  6. Datatable导出Excel

    ; IRow headerRow = sheet.CreateRow(); ; ; ; iRowIndex++; } ; i < icolIndex; i++) { sheet.AutoSize ...

  7. 使用NPOI导出DataTable到Excel

    使用C#对DataTable导出到Excel是我们工作当中比较多用到的场景,微软提供了Microsoft.Office.Interop.Excel组件可以进行操作,但是该组件在数据量大的时候速度很慢, ...

  8. DataTable 导出到 Excel 类

    底层类: #region DataTable 导出到 Excel /// <summary> /// DataTable 导出到 Excel /// </summary> // ...

  9. NPOI通过DataTable导出和读取Excel

    Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导出到Excel的类,时不时还会维护一个导入类.以下是时不时就会出现的问题: 导出问题: 如果是asp.net,你得 ...

随机推荐

  1. iOS崩溃日志

    今天看crash report ,有这样两个crash: 调用 stopUpdatingLocation 函数的是一个CLLocationManager 类型的对象,为什么报错的时候会把这个对象转成N ...

  2. rpm卸载包遭遇 specifies multiple packages 错误

    使用 rpm删除软件时报错如下: [root@hostxxlidan]# rpm -qa |grep -i mysqlmysql-devel-5.0.95-5.el5_9mysql-devel-5.0 ...

  3. XAMPP添加多个站点之httpd-vhosts.conf 设置

    1.在xampp\apache\conf\httpd.conf设置路径DocumentRoot和Directory 必须与xampp\apache\conf\extra\httpd-vhosts.co ...

  4. [洛谷P3929]SAC E#1 - 一道神题 Sequence1

    题目大意:给你一串数列,问你能否改变1个数或不改,使它变成波动数列? 一个长度为n的波动数列满足对于任何i(1 <= i < n),均有: a[2i-1] <= a[2i] 且 a[ ...

  5. uname---用于打印当前系统相关信息

    uname命令用于打印当前系统相关信息(内核版本号.硬件架构.主机名称和操作系统类型等). 语法 uname(选项) 选项 -a或--all:显示全部的信息: -m或--machine:显示电脑类型: ...

  6. scrapy xpath选择器多级选择错误

    在学习scrapy中用xpath提取网页内容时,有时要先提取出一整个行标签内容,再从行标签里寻找目标内容.出现一个错误. 错误代码: def parse(self, response): sel = ...

  7. HBase快照、Snapshots 淘宝快照

    淘宝在2011年之前所有的后端持久化存储基本上与我们所认知的意义,  大量存于 mysql .少量 oracle mongdb 等,使用mysql 的原因相信各位也很熟悉了.  开源.社区庞大.解决方 ...

  8. 关于Windows7下创建Cocos2D-X项目的小问题

    "新版的Cocos2D-X"已经不支持用上述脚本来创建工程了,而是改为用create-project.py来创建...命令格式: python create-project.py ...

  9. BZOJ2895: 球队预算

    [传送门:BZOJ2895] 简要题意: 在一个篮球联赛里,有n支球队,球队的支出是和他们的胜负场次有关系的,具体来说,第i支球队的赛季总支出是Ci*x^2+Di*y^2,Di<=Ci.(赢得多 ...

  10. Django 框架篇(四) : 视图(view)详解 以及 路由系统(url)

    |--Django的View(视图) |-- CBV和FBV: |-- 给视图增加装饰器: |-- request对象: |-- response对象: |-- Django的路由系统(url): | ...