导出EXCEL(转转)
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[]; int cnt = dt.Rows.Count;
int columncnt = dt.Columns.Count; // *****************获取数据********************
object[,] objData = new Object[cnt + , columncnt]; // 创建缓存数据
// 获取列标题
for (int i = ; i < columncnt; i++)
{
objData[, i] = dt.Columns[i].ColumnName;
}
// 获取具体数据
for (int i = ; i < cnt; i++)
{
System.Data.DataRow dr = dt.Rows[i];
for (int j = ; j < columncnt; j++)
{
objData[i + , j] = dr[j];
}
} //********************* 写入Excel******************
Range r = ws.get_Range(app.Cells[, ], app.Cells[cnt + , 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 > ) //总行数大于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 = ; 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 = ; j < dt.Columns.Count; j++)
{
content.Append("<td><b>" + dt.Columns[j].ColumnName + "</b></td>");
}
}
content.Append("</tr>\n"); for (int j = ; j < dt.Rows.Count; j++)
{
content.Append("<tr>");
for (int k = ; 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) == ))
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(" ", "");
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();
}
}
}
导出EXCEL(转转)的更多相关文章
- C#使用Aspose.Cells导出Excel简单实现
首先,需要添加引用Aspose.Cells.dll,官网下载地址:http://downloads.aspose.com/cells/net 将DataTable导出Xlsx格式的文件下载(网页输出) ...
- 利用poi导出Excel
import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.lang.r ...
- [django]数据导出excel升级强化版(很强大!)
不多说了,原理采用xlwt导出excel文件,所谓的强化版指的是实现在网页上选择一定条件导出对应的数据 之前我的博文出过这类文章,但只是实现导出数据,这次左思右想,再加上网上的搜索,终于找出方法实现条 ...
- NPOI导出Excel
using System;using System.Collections.Generic;using System.Linq;using System.Text;#region NPOIusing ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- asp.net DataTable导出Excel 自定义列名
1.添加引用NPOI.dll 2.cs文件头部添加 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System.IO; 3.代码如 ...
- Aspose.Cells导出Excel(1)
利用Aspose.Cells导出excel 注意的问题 1.DataTable的处理 2.进行编码,便于中文名文件下载 3.别忘了Aspose.Cells.dll(可以自己在网上搜索) public ...
- 前端导出Excel兼容写法
今天整理出在Web前端导出Excel的写法,写了一个工具类,对各个浏览器进行了兼容. 首先,导出的数据来源可能有两种: 1. 页面的HTML内容(一般是table) 2. 纯数据 PS:不同的数据源, ...
- JS导出excel 兼容ie、chrome、firefox
运用js实现将页面中的table导出为excel文件,页面显示如下: 导出的excel文件显示如下: 实现代码: <!DOCTYPE html> <html> <head ...
随机推荐
- LayerDrawable 资源
与 StateListDrawable 有点类似,LayerDrawable 也可包含一个 Drawable 数组,因此系统 将会按这些 Drawable 对象的数组顺序来绘制它们,索引最大的 Dra ...
- COJ 0343 WZJ的公司(二)
传送门:http://oj.cnuschool.org.cn/oj/home/problem.htm?problemID=313 试题描述: WZJ的公司放假了!为了保证假期期间公司的安全,WZJ决定 ...
- 基于Minifilter框架的文件过滤驱动理解
概述 Minifilter即File System Minifilter Drivers,是Windows为了简化第三方开发人员开发文件过滤驱动而提供的一套框架,这个框架依赖于一个称之为Filter ...
- libevent的简单应用【转载】
本文转载自: http://blog.csdn.net/liuguanghui1988/article/details/7090531 Libevent的应用主要围绕几大事件:超时事件.信号事件.读/ ...
- log4j级别输出
log4j 我们知道: log4j.logger.XX cover ==> log4j.rootLogger log4j.appender.XX.Threshold决定了最低接收级别 也就是说 ...
- angular指令浅谈
今天在闲暇时间再次对angularjs的指令进行了初探,不探不知道一探吓一跳啊, 就一个简单的指令整整难住我了两个小时,先不说代码的逻辑是否复杂,就一些内部的一些实现让我看起来都是头疼的不行啊,不过最 ...
- Sql 语句添加字段、修改字段类型、默认值语法
Sql 语句添加字段 ,) not null --修改类型 alter Table bbs ) Sql 语句修改默认值 alter table 表名 drop constraint 约束名字 --删除 ...
- Sending Signals to Processes with kill, killall, and pkill
The Linux kernel allows many signals to be sent to processes. Use man 7 signals for a complete overv ...
- Debian耳机声音问题
Debian耳机声音问题 关于Debian声音问题 debian testing基本系统安装无声音问题解决 耳机声音问题 之前耳机声音一直正常,使用部分软件更改声卡设置后,计算机可以播放外音,但是耳机 ...
- Tomcat相关目录及配置文件总结
Tomcat根目录介绍 [bin]目录主要是用来存放tomcat的命令,主要有两大类,一类是以.sh结尾的(linux命令),另一类是以.bat结尾的(windows命令). 很多环境变量的 ...