华易动力天津网站制作公司 免费咨询热线:400-0022-823 电话:022-28261501 28335110
地址:天津市河西区围堤道146号华盛广场B座22楼
点击这里给我发消息  点击这里给我发消息  点击这里给我发消息
  首页 关于我们 建网站:从这里开始 域名空间服务 案例展示 新闻中心 网站制作知识 网站设计技巧 人才招聘 联系我们  
  网站制作知识
程序制作
数据库知识
域名空间知识
SEO网站优化
天津网站制作方案 更多..
如何获得了大量的好的外链资源
常见的长尾关键词组合方法
如何利用百度平台获取流量
营销优化型网站的简介
新顶级域名的形式
网站建设分为如下八步
网站专题设计
关于门户网站设计方案
华易动力售后服务规范
服务器机房介绍
优秀客户展示(排名无先后) 更多..
环化(天津)燃气设备安装有限公司
天津市国信投资担保有限公司
天津城市职业学院
天津大学EMBA
南开大学CID
北京同仁堂天津药店有限公司
金权道(天津)餐饮管理有限公司
天津市友好合作城市企业促进会
天津天大求实电力新技术股份有限公司
天津红旗农贸投资控股有限公司
天津二人锅餐饮管理有限公司
天津市滨湖剧院
渤海产业投资基金管理有限公司
天津天富软管工业有限公司
新闻中心-行业资讯 更多..
· 企业为什么要做APP   2016-11-24
· 如何搭配网站   2016-11-16
· css表单布局的五个小技巧   2016-11-16
· 服务器维护的重点   2016-11-14
· 如何建设你想要的网站类型   2016-11-14
· 阿里设计师用这2方法提升设计创新力   2016-11-3
· 我们看过的各种设计理论法则   2016-11-3
· Windows 8设计时的安全性   2013-12-27
· 未来网站技术的发展   2013-10-12
· 企业网站建设规划   2013-7-30
全部信息 当前位置:首页网站制作知识 → 详细内容
在Asp.net用C#建立动态Excel
更新时间:2013/1/17 点击:1089次

在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 ;
}
}

 

 
  公司总机:022-28261501 28335110
客户服务邮箱:service@nfree.cn,手机直线:15822335163
CopyRight 2006~2024 All Rights Reserved 天津市华易动力信息科技有限公司
地址:天津市河西区围堤道146号华盛广场B座22楼 邮编:300202

津公网安备 12010302001042号


在线QQ(售前咨询)
点击这里给我发消息  点击这里给我发消息  点击这里给我发消息