在Asp.net用C#建立动态Excel
在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 ;
}
}
-翻译匆忙 ,有误请谅解 ,欢迎指点,探讨 ---小徐
上一篇: AE怎么制作沙漏慢慢漏掉的文字动画?
下一篇: 中医推荐补肾养肺药膳 白果滋润皮肤治哮喘