|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
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;
}
}
-翻译匆仓促,有误请体谅,接待指导,切磋
一个很大的类库。应用程序之所以难以跨平台,在于直接调用了特定平台的接口,而一个巨大的类库,就能极大地减少应用程序对平台的依赖。 |
|