动态网站制作指南 [  QQ表情  ]
[ 投票调查 ]
[ 企业邮箱 ]
[ 网站空间 ]
网络编程 | 站长之家 | 网页制作 | 图形图象 | 操作系统 | 冲浪宝典 | 软件教学 | 网络办公 | 邮件系统 | 网络安全 | 认证考试 | 系统进程
ASP源码 | .Net源码 | PHP源码 | JSP源码 | JAVA源码 | CGI源码 | VB源码 | C++源码 | Delphi源码 | PB源码 | VF源码 | 汇编 | 服务器
Firefox | IE | Maxthon | 迅雷 | 电驴 | BitComet | FlashGet | QQ | QQ空间 | Vista | 输入法 | Ghost | Word | Excel | wps | Powerpoint
asp | .net | php | jsp | Sql | c# | Ajax | xml | Dreamweaver | FrontPages | Javascript | css | photoshop | fireworks | Flash | Cad | Discuz!
当前位置 > 网站建设学院 > 网络编程 > ASP.NET技巧
Tag:注入,存储过程,分页,安全,优化,xmlhttp,fso,jmail,application,session,防盗链,stream,无组件,组件,md5,乱码,缓存,加密,验证码,算法,cookies,ubb,正则表达式,水印,索引,日志,压缩,base64,url重写,上传,控件,Web.config,JDBC,函数,内存,PDF,迁移,结构,破解,编译,配置,进程,分词,IIS,Apache,Tomcat,phpmyadmin,Gzip,触发器,socket
网络编程:ASP教程,ASP.NET教程,PHP教程,JSP教程,C#教程,数据库,XML教程,Ajax,Java,Perl,Shell,VB教程,Delphi,C/C++教程,软件工程,J2EE/J2ME,移动开发
文章搜索服务
邮件订阅
输入你的邮件地址,
你将不会错过任何关于:
[ ASP.NET技巧 ]的信息

本月文章推荐
.ACCESS在Web.config里设置连接字.
.ASP.NET2.0服务器控件之捕获回传.
.DataSet 添加数据集、行、列、主.
.Asp.Net细节性问题精萃.
.ASP.NET 2.0角色及成员管理 .
.asp.net 水晶报表-主从表关联问题.
.利用ASP.NET技术动态生成HTML页面.
.写个偷全国公交数据库的程序 .
.使用ASP.NET2.0的ReportViewer查.
.在ASP.NET程序中创建唯一序号.
.ASPX接收WINDOWS应用程序以POST方.
.过滤ASP.NET输出HTML中的无用空格.
.ASP.NET动态创建控件之绝境求生.
.ASP.Net防止刷新自动触发事件的解.
.获取本机上配置好的Oracle服务名.
.ASP.NET之上传文件管理策略.
..NET 应用程序的性能提升应用技巧.
.ASP.NET 崩溃-SiteMap中疯狂的循.
.给Asp.Net初学者的关于继承和多态.
.编写高性能Web应用程序的10个入门.

在Asp.net用C#建立动态Excel(外文翻译)

发表日期:2006-6-1 |


在Asp.net中建立本地的Excel表,并由服务器向外传播是容易实现的,而删除掉嵌入的Excel.exe进程是困难的。所以 你不要打开任务管理器 ,看Excel.exe进程相关的东西是否还在内存里面。我在这里提供一个解决方案 ,里面提供了两个方法 :
"CreateExcelWorkbook"(说明 建立Excel工作簿) 这个方法 运行一个存储过程 ,返回一个DataReader 并根据DataReader 来生成一个Excel工作簿 ,并保存到文件系统中,创建一个“download”连接,这样 用户就可以将Excel表导入到浏览器中也可以直接下载到机器上。

第二个方法:GenerateCSVReport 本质上是做同样的一件事情,仅仅是保存的文件的CSV格式 。仍然 导入到Excel中,CSV代码能解决一个开发中的普片的问题:你有一列 里面倒入了多个零,CSV代码能保证零不变空 。(说明: 就是在Excel表中多个零的值 不能保存的问题)

 

   在可以下载的解决方案中,包含一个有效的类 ” SPGen” 能运行存储过程并返回DataReader ,一个移除文件的方法 能删除早先于一个特定的时间值。下面出现的主要的方法就是CreateExcelWorkbook

 

   注意:你必须知道 在运行这个页面的时候,你可能需要能在WebSever 服务器的文件系统中写 Excel,Csv文件的管理员的权限。处理这个问题的最简单的方法就是运行这个页面在自己的文件夹里面并包括自己的配置文件。并在配置文件中添加下面的元素<identity impersonate ="true" ... 。你仍然需要物理文件夹的访问控制列表(ACL)的写的权限,只有这样运行的页面的身份有写的权限,最后,你需要设置一个Com连接到Excel 9.0 or Excel 10 类型库 ,VS.NET 将为你生成一个装配件。我相信 微软在他们Office网站上有一个连接,可以下载到微软的初始的装配件 。(可能不准,我的理解是面向.net的装配件)

 

<identity impersonate="true" userName="adminuser" password="adminpass" />

 

特别注意 下面的代码块的作用是清除Excel的对象。

 

// Need all following code to clean up and extingush all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
oSheet=null;
oWB=null;
oXL = null;
GC.Collect(); // force final cleanup!

 

 

这是必须的 ,因为oSheet", "oWb" , 'oRng", 等等 对象也是COM的实例,我们需要

Marshal类的ReleaseComObject的方法把它们从.NET去掉

private void CreateExcelWorkbook(string spName, SqlParameter[] parms)
{
string strCurrentDir = Server.MapPath(".") + "\\";
RemoveFiles(strCurrentDir); // utility method to clean up old files
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

try
{
GC.Collect();// clean up any other excel guys hangin' around...
oXL = new Excel.Application();
oXL.Visible = false;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//get our Data

string strConnect = System.Configuration.ConfigurationSettings.AppSettings["connectString"];
SPGen sg = new SPGen(strConnect,spName,parms);
SqlDataReader myReader = sg.RunReader();
// Create Header and sheet...
int iRow =2;
for(int j=0;j<myReader.FieldCount;j++)
{
oSheet.Cells[1, j+1] = myReader.GetName(j).ToString();
}
// build the sheet contents
while (myReader.Read())
{
for(int k=0;k < myReader.FieldCount;k++)
{
oSheet.Cells[iRow,k+1]= myReader.GetValue(k).ToString();
}
iRow++;
}// end while
myReader.Close();
myReader=null;
//Format A1:Z1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment =Excel.XlVAlign.xlVAlignCenter;
//AutoFit columns A:Z.
oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
string strFile ="report" + System.DateTime.Now.Ticks.ToString() +".xls";
oWB.SaveAs( strCurrentDir + strFile,Excel.XlFileFormat.xlWorkbookNormal,
     null,null,false,false,Excel.XlSaveAsAccessMode.xlShared,false,false,null,null,null);
// Need all following code to clean up and extingush all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
oSheet=null;
oWB=null;
oXL = null;
GC.Collect(); // force final cleanup!
string strMachineName = Request.ServerVariables["SERVER_NAME"];
errLabel.Text="<A href=http://" + strMachineName +"/ExcelGen/" +strFile + ">Download Report</a>";

}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
errLabel.Text= errorMessage ;
}
}

 

 

 

 

   下面是原文章

Create Dynamic ASP.NET Excel Workbooks In C#

By Peter A. Bromberg, Ph.D.
Printer - Friendly Version
 
 

There is also, in the downloadable solution, a utility class "SPGen" that handles running stored

Generating native Excel spreadsheets from your web server is not that difficult with ASP.NET. What can be difficult is making instances of Excel.exe go away so you don't open up TaskMgr and see 123 instances of EXCEL.EXE still sitting in memory. I provide here a solution that has two methods, "CreateExcelWorkbook", which runs a stored proceduire that returns a DataReader and assembles a native Excel Workbook from it, saves it to the filesystem, and creates a "Download" link so the user can either load the report into Excel in their browser, or download the XLS file. The second method, GenerateCSVReport, does essentially the same thing but creates a CSV file that will, of course, also load into Excel. The CSV code correctly handles a common developer problem in that if you have a column that has leading zeroes, they are preserved.

 

procedures and returning DataReaders, and a RemoveFiles utility method that cleans up any XLS or CSV file older than the specified number of minutes. The key method presented below is the CreateExcelWorkbook method.

NOTE: You should be aware that you will probably need to run this page under an account that has administrative privileges as it needs write permissions to store the generated Excel or CSV files on the webserver's file system. Probably the easiest way to handle this is to have the page in its own folder with its own web.config, and insert an <identity impersonate ="true" ... elment. You may also need to enable ACL permissions on the physical folder as well so that the identity the page runs under has write permissions. Finally, you'll need to set a COM reference to the Excel 9.0 or Excel 10 Typelibrary and let VS.NET generate the Interop assemblies for you. I believe MS also has a link on their Office site where you can download the Office primary Interop Assemblies.

 

<identity impersonate="true" userName="adminuser" password="adminpass" />

 

Note especially the code block that does the "cleanup" of the Excel objects:

// Need all following code to clean up and extingush all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
oSheet=null;
oWB=null;
oXL = null;
GC.Collect(); // force final cleanup!

 

This is necessary because all those littlle objects "oSheet", "oWb" , 'oRng", etc. are all COM instances and we need to use the InteropServices ReleaseComObject method of the Marshal class to get rid of them in .NET.

private void CreateExcelWorkbook(string spName, SqlParameter[] parms)
{
string strCurrentDir = Server.MapPath(".") + "\\";
RemoveFiles(strCurrentDir); // utility method to clean up old files
Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

try
{
GC.Collect();// clean up any other excel guys hangin' around...
oXL = new Excel.Application();
oXL.Visible = false;
//Get a new workbook.
oWB = (Excel._Workbook)(oXL.Workbooks.Add( Missing.Value ));
oSheet = (Excel._Worksheet)oWB.ActiveSheet;
//get our Data

string strConnect = System.Configuration.ConfigurationSettings.AppSettings["connectString"];
SPGen sg = new SPGen(strConnect,spName,parms);
SqlDataReader myReader = sg.RunReader();
// Create Header and sheet...
int iRow =2;
for(int j=0;j<myReader.FieldCount;j++)
{
oSheet.Cells[1, j+1] = myReader.GetName(j).ToString();
}
// build the sheet contents
while (myReader.Read())
{
for(int k=0;k < myReader.FieldCount;k++)
{
oSheet.Cells[iRow,k+1]= myReader.GetValue(k).ToString();
}
iRow++;
}// end while
myReader.Close();
myReader=null;
//Format A1:Z1 as bold, vertical alignment = center.
oSheet.get_Range("A1", "Z1").Font.Bold = true;
oSheet.get_Range("A1", "Z1").VerticalAlignment =Excel.XlVAlign.xlVAlignCenter;
//AutoFit columns A:Z.
oRng = oSheet.get_Range("A1", "Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible = false;
oXL.UserControl = false;
string strFile ="report" + System.DateTime.Now.Ticks.ToString() +".xls";
oWB.SaveAs( strCurrentDir + strFile,Excel.XlFileFormat.xlWorkbookNormal,
     null,null,false,false,Excel.XlSaveAsAccessMode.xlShared,false,false,null,null,null);
// Need all following code to clean up and extingush all references!!!
oWB.Close(null,null,null);
oXL.Workbooks.Close();
oXL.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject (oRng);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oXL);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject (oWB);
oSheet=null;
oWB=null;
oXL = null;
GC.Collect(); // force final cleanup!
string strMachineName = Request.ServerVariables["SERVER_NAME"];
errLabel.Text="<A href=http://" + strMachineName +"/ExcelGen/" +strFile + ">Download Report</a>";

}
catch( Exception theException )
{
String errorMessage;
errorMessage = "Error: ";
errorMessage = String.Concat( errorMessage, theException.Message );
errorMessage = String.Concat( errorMessage, " Line: " );
errorMessage = String.Concat( errorMessage, theException.Source );
errLabel.Text= errorMessage ;
}
}
                   
-翻译匆忙 ,有误请谅解 ,欢迎指点,探讨 ---小徐

http://macroxu-1982.cnblogs.com/archive/2006/05/31/413879.html

上一篇:ASP.NET实现匿名访问控制 人气:5499
下一篇:ASP.NET服务器控件之视图状态 人气:5396
浏览全部Asp.net的内容 Dreamweaver插件下载 常用网页广告代码全集
  最新网站源码 最新软件下载
2008-10-6 Menalto Gallery v2.3 Rc2 多国语
2008-10-6 花香盈路(Hxcms) v9.0
2008-10-6 华军软件下载系统 v1.5
2008-10-6 e107 v0.7.13
2008-10-6 (开源PHP框架) CodeIgniter v1.6
2008-10-6 PHP在线考试系统PPExam v1.2.6 b
2008-10-6 SiteDynamic企业网站管理系统 v1
2008-10-6 WebPlayer9 P2P视频点播电影整站
2008-10-6 BCMS v1.1 测试版
2008-9-29 酷狗音乐(原KuGoo)2008 v5.310 正
2008-9-29 QQTab 1.1
2008-9-29 网络传送带 Net Transport 2.64a
2008-9-29 谷歌金山词霸v1.8
2008-9-29 TweakVI 1.0 Build 1090
2008-9-29 ACDSee Pro 2.5 Build 333 汉化绿
2008-9-29 Winamp v5.541(2189) 周明波简体
2008-9-27 CCleaner 2.12.651
2008-9-27 Mozilla Thunderbird 2.0.0.17 英
  发表评论
姓 名: 验证码:
内 容:
站长工具:网站收录查询 | Google PR查询 | ALEXA排名查询 | CSS在线编辑器 | 广告代码 | js/vbs加密 | md5加密 | 进制转换 | UTF-8 转换工具 | Html转换js | Html转换asp | Html转换php | Html转换perl
实用工具:汉字翻译拼音 | 拼音字典 | 符号对照表 | 个税计算 | 实时汇率查询换算 | 经典小工具 | 汉字简繁转换 | 普通单位换算 | 公制单位换算 | 生辰老黄历 | 国内电话区号 | 国家代码与域名缩写 | 文字加密解密 | 健康查询 | 万年历 | 汉字横竖排版 | 手机号码查询 | 计算器 | ip搜索
业务联系 | 广告刊登 | 频道合作 | 投稿荐稿 | 联系方式 | 加入收藏 | RSS订阅
Copyright © 2000-2008 www.knowsky.com All rights reserved | 网络实名:动态网站制作指南 | 沪ICP备05001343号
ホームページ制作 不動産検索システム 求人情報
防水工事·改修工事 フットサル大会 探偵
SEO対策 中国語教室 ホームページ作成