仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 613|回复: 8
打印 上一主题 下一主题

[学习教程] ASP.NET教程之在Asp.net用C#创建静态Excel

[复制链接]
若天明 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-16 22:39:45 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
一般的指的.net就是跟java相对的那种,主要是做企业级应用的。你如果想学这个,主要就是学C#和数据库。(ASP.NET好像很重要的,应该也要学的,ASP.NET上好像可以结合VB和C#等多种语言,但是微软主推C#)asp.net|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文件的办理员的权限。处置这个成绩的最复杂的办法就是运转这个页面在本人的文件夹内里并包含本人的设置文件。并在设置文件中增加上面的元素<identityimpersonate="true"...。你仍旧必要物理文件夹的会见把持列表(ACL)的写的权限,只要如许运转的页面的身份有写的权限,最初,你必要设置一个Com毗连到Excel9.0orExcel10范例库,VS.NET将为你天生一个拆卸件。我信任微软在他们Office网站上有一个毗连,能够下载到微软的初始的拆卸件 。(大概禁绝,我的了解是面向.net的拆卸件)
<identityimpersonate="true"userName="adminuser"password="adminpass"/>
出格注重上面的代码块的感化是扫除Excel的工具。
//Needallfollowingcodetocleanupandextingushallreferences!!!
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();//forcefinalcleanup!
这是必需的,由于oSheet","oWb",oRng",等等工具也是COM的实例,我们必要
Marshal类的ReleaseComObject的办法把它们从.NET往失落
privatevoidCreateExcelWorkbook(stringspName,SqlParameter[]parms)
{
stringstrCurrentDir=Server.MapPath(".")+"";
RemoveFiles(strCurrentDir);//utilitymethodtocleanupoldfiles
Excel.ApplicationoXL;
Excel._WorkbookoWB;
Excel._WorksheetoSheet;
Excel.RangeoRng;
try
{
GC.Collect();//cleanupanyotherexcelguyshanginaround...
oXL=newExcel.Application();
oXL.Visible=false;
//Getanewworkbook.
oWB=(Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet=(Excel._Worksheet)oWB.ActiveSheet;
//getourData
stringstrConnect=System.Configuration.ConfigurationSettings.AppSettings["connectString"];
SPGensg=newSPGen(strConnect,spName,parms);
SqlDataReadermyReader=sg.RunReader();
//CreateHeaderandsheet...
intiRow=2;
for(intj=0;j<myReader.FieldCount;j++)
{
oSheet.Cells[1,j+1]=myReader.GetName(j).ToString();
}
//buildthesheetcontents
while(myReader.Read())
{
for(intk=0;k<myReader.FieldCount;k++)
{
oSheet.Cells[iRow,k+1]=myReader.GetValue(k).ToString();
}
iRow++;
}//endwhile
myReader.Close();
myReader=null;
//FormatA1:Z1asbold,verticalalignment=center.
oSheet.get_Range("A1","Z1").Font.Bold=true;
oSheet.get_Range("A1","Z1").VerticalAlignment=Excel.XlVAlign.xlVAlignCenter;
//AutoFitcolumnsA:Z.
oRng=oSheet.get_Range("A1","Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible=false;
oXL.UserControl=false;
stringstrFile="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);
//Needallfollowingcodetocleanupandextingushallreferences!!!
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();//forcefinalcleanup!
stringstrMachineName=Request.ServerVariables["SERVER_NAME"];
errLabel.Text="<Ahref=http://"+strMachineName+"/ExcelGen/"+strFile+">DownloadReport</a>";
}
catch(ExceptiontheException)
{
StringerrorMessage;
errorMessage="Error:";
errorMessage=String.Concat(errorMessage,theException.Message);
errorMessage=String.Concat(errorMessage,"Line:");
errorMessage=String.Concat(errorMessage,theException.Source);
errLabel.Text=errorMessage;
}
}
上面是原文章
CreateDynamicASP.NETExcelWorkbooksInC#
ByPeterA.Bromberg,Ph.D.
Printer-FriendlyVersion

Thereisalso,inthedownloadablesolution,autilityclass"SPGen"thathandlesrunningstored
GeneratingnativeExcelspreadsheetsfromyourwebserverisnotthatdifficultwithASP.NET.WhatcanbedifficultismakinginstancesofExcel.exegoawaysoyoudontopenupTaskMgrandsee123instancesofEXCEL.EXEstillsittinginmemory.Iprovidehereasolutionthathastwomethods,"CreateExcelWorkbook",whichrunsastoredproceduirethatreturnsaDataReaderandassemblesanativeExcelWorkbookfromit,savesittothefilesystem,andcreatesa"Download"linksotheusercaneitherloadthereportintoExcelintheirbrowser,ordownloadtheXLSfile.Thesecondmethod,GenerateCSVReport,doesessentiallythesamethingbutcreatesaCSVfilethatwill,ofcourse,alsoloadintoExcel.TheCSVcodecorrectlyhandlesacommondeveloperprobleminthatifyouhaveacolumnthathasleadingzeroes,theyarepreserved.
proceduresandreturningDataReaders,andaRemoveFilesutilitymethodthatcleansupanyXLSorCSVfileolderthanthespecifiednumberofminutes.ThekeymethodpresentedbelowistheCreateExcelWorkbookmethod.
NOTE:YoushouldbeawarethatyouwillprobablyneedtorunthispageunderanaccountthathasadministrativeprivilegesasitneedswritepermissionstostorethegeneratedExcelorCSVfilesonthewebserversfilesystem.Probablytheeasiestwaytohandlethisistohavethepageinitsownfolderwithitsownweb.config,andinsertan<identityimpersonate="true"...elment.YoumayalsoneedtoenableACLpermissionsonthephysicalfolderaswellsothattheidentitythepagerunsunderhaswritepermissions.Finally,youllneedtosetaCOMreferencetotheExcel9.0orExcel10TypelibraryandletVS.NETgeneratetheInteropassembliesforyou.IbelieveMSalsohasalinkontheirOfficesitewhereyoucandownloadtheOfficeprimaryInteropAssemblies.
<identityimpersonate="true"userName="adminuser"password="adminpass"/>
Noteespeciallythecodeblockthatdoesthe"cleanup"oftheExcelobjects:
//Needallfollowingcodetocleanupandextingushallreferences!!!
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();//forcefinalcleanup!
Thisisnecessarybecauseallthoselittlleobjects"oSheet","oWb",oRng",etc.areallCOMinstancesandweneedtousetheInteropServicesReleaseComObjectmethodoftheMarshalclasstogetridofthemin.NET.
privatevoidCreateExcelWorkbook(stringspName,SqlParameter[]parms)
{
stringstrCurrentDir=Server.MapPath(".")+"";
RemoveFiles(strCurrentDir);//utilitymethodtocleanupoldfiles
Excel.ApplicationoXL;
Excel._WorkbookoWB;
Excel._WorksheetoSheet;
Excel.RangeoRng;
try
{
GC.Collect();//cleanupanyotherexcelguyshanginaround...
oXL=newExcel.Application();
oXL.Visible=false;
//Getanewworkbook.
oWB=(Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));
oSheet=(Excel._Worksheet)oWB.ActiveSheet;
//getourData
stringstrConnect=System.Configuration.ConfigurationSettings.AppSettings["connectString"];
SPGensg=newSPGen(strConnect,spName,parms);
SqlDataReadermyReader=sg.RunReader();
//CreateHeaderandsheet...
intiRow=2;
for(intj=0;j<myReader.FieldCount;j++)
{
oSheet.Cells[1,j+1]=myReader.GetName(j).ToString();
}
//buildthesheetcontents
while(myReader.Read())
{
for(intk=0;k<myReader.FieldCount;k++)
{
oSheet.Cells[iRow,k+1]=myReader.GetValue(k).ToString();
}
iRow++;
}//endwhile
myReader.Close();
myReader=null;
//FormatA1:Z1asbold,verticalalignment=center.
oSheet.get_Range("A1","Z1").Font.Bold=true;
oSheet.get_Range("A1","Z1").VerticalAlignment=Excel.XlVAlign.xlVAlignCenter;
//AutoFitcolumnsA:Z.
oRng=oSheet.get_Range("A1","Z1");
oRng.EntireColumn.AutoFit();
oXL.Visible=false;
oXL.UserControl=false;
stringstrFile="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);
//Needallfollowingcodetocleanupandextingushallreferences!!!
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();//forcefinalcleanup!
stringstrMachineName=Request.ServerVariables["SERVER_NAME"];
errLabel.Text="<Ahref=http://"+strMachineName+"/ExcelGen/"+strFile+">DownloadReport</a>";
}
catch(ExceptiontheException)
{
StringerrorMessage;
errorMessage="Error:";
errorMessage=String.Concat(errorMessage,theException.Message);
errorMessage=String.Concat(errorMessage,"Line:");
errorMessage=String.Concat(errorMessage,theException.Source);
errLabel.Text=errorMessage;
}
}
  -翻译匆仓促,有误请体谅,接待指导,切磋
一个很大的类库。应用程序之所以难以跨平台,在于直接调用了特定平台的接口,而一个巨大的类库,就能极大地减少应用程序对平台的依赖。
柔情似水 该用户已被删除
沙发
发表于 2015-1-19 20:56:27 | 只看该作者
提供基于组件、事件驱动的可编程网络表单,大大简化了编程。还可以用ASP.NET建立网络服务。
海妖 该用户已被删除
板凳
发表于 2015-1-25 05:23:04 | 只看该作者
ASP.net1.1和2.0在程序上的语法也有很大不同,现在2.0属于新出来的,不知道半年后会不会有3.0(说笑一下)。Windows2003系统自动支持ASP和ASP.net环境,不用安装任何程序。Asp.net属于编译语言。ASP的最大不同(ASP属于解释语言)。
分手快乐 该用户已被删除
地板
发表于 2015-2-2 14:47:51 | 只看该作者
Asp.net脚本的出现,为ASP空间带来了更高的稳定性,同时也为程序员建站提供更高环境!
兰色精灵 该用户已被删除
5#
发表于 2015-2-7 23:05:23 | 只看该作者
现在主流的网站开发语言无外乎asp、php、asp.net、jsp等。
莫相离 该用户已被删除
6#
发表于 2015-2-23 14:53:58 | 只看该作者
ASP在执行的时候,是由IIS调用程序引擎,解释执行嵌在HTML中的ASP代码,最终将结果和原来的HTML一同送往客户端。
谁可相欹 该用户已被删除
7#
发表于 2015-3-7 09:27:25 | 只看该作者
asp.net空间的支持有:ASP.NET1.1/虚拟目录/MicrosoftFrontPage2000扩展/CDONTS,同时他的网站上也提供了Asp.net的使用详解和程序源代码,相信对使用ASP.NET编程的程序员来说会非常有用哦!
蒙在股里 该用户已被删除
8#
发表于 2015-3-14 18:35:51 | 只看该作者
但是目前在CGI中使用的最为广泛的是Perl语言。所以,狭义上所指的CGI程序一般都是指Perl程序,一般CGI程序的后缀都是.pl或者.cgi。
乐观 该用户已被删除
9#
发表于 2015-3-21 13:36:47 | 只看该作者
代码逻辑混乱,难于管理:由于ASP是脚本语言混合html编程,所以你很难看清代码的逻辑关系,并且随着程序的复杂性增加,使得代码的管理十分困难,甚至超出一个程序员所能达到的管理能力,从而造成出错或这样那样的问题。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-9-29 18:20

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表