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

}

}

-翻译匆忙 ,有误请谅解 ,欢迎指点,探讨 ---小徐

(0)

相关推荐

  • C#使用Ado.net读取Excel表的方法

    本文实例讲述了C#使用Ado.net读取Excel表的方法.分享给大家供大家参考.具体分析如下: 微软NET提供了一个交互的方法,通过使用ADO.NET与Microsoft Office程序.可以使用内置的OLEDB来访问Excel的XLS表格.下面的例子演示了如何在C#编程读取Excel工作表.需要引用System.Data.OleDb库 using System; using System.Data.OleDb; namespace ConsoleApplication1 { class P

  • ASP.NET(C#)读取Excel的文件内容

    .xls格式       Office2003及以下版本 .xlsx格式 Office2007 及以上版本 .csv格式       以逗号分隔的字符串文本(可以将上述两种文件类型另存为此格式) 读取前两种格式和读取后一种格式会用两种不同的方法. 下面看程序:页面前台: 复制代码 代码如下: <div>       <%-- 文件上传控件  用于将要读取的文件上传 并通过此控件获取文件的信息--%>      <asp:FileUpload ID="fileSele

  • ASP.NET(C#) 读取EXCEL另加解决日期问题的方法分享

    使用OLEDB可以对excel文件进行读取,我们只要把该excel文件作为数据源即可. 一 在D盘创建excel文件test.xls: 二 将工作表Sheet1的内容读取到DataSet 复制代码 代码如下: string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/test.xls;"+   "Extended Properties='Excel 8.0'"; DataSet ds = ne

  • C#.net编程创建Access文件和Excel文件的方法详解

    本文实例讲述了C#.net编程创建Access文件和Excel文件的方法.分享给大家供大家参考,具体如下: 一些系统可能需求把数据导出到Access或者Excel文件格式,以方便的传递数据.打印等. Excel 文件或者 Access这两种需要导出的文件可能并不是事先就存在的,这就需要我们自己编程生成他们,下面整理一下生成这两个文件的一些方法,只罗列最常用的.并不全. 一.首先生成Excel文件. 方案一.如果用Excel保存的只是二维数据,也就是把他当数据库的来用. 最简单,你不用引用任何额外

  • asp.net(C#) Access 数据操作类

    复制代码 代码如下: using System; using System.Configuration; using System.Data; using System.Data.OleDb; using System.Xml; using System.Collections; namespace Website.Command { /// <summary> /// WSplus 的摘要说明. /// </summary> public class AccessClass :

  • ADO.NET 读取EXCEL的实现代码((c#))

    // 连接字符串 复制代码 代码如下: // 连接字符串                     string xlsPath = Server.MapPath("~/app_data/somefile.xls"); // 绝对物理路径         string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;" +                         "Extended Properties=Exc

  • ACCESS的参数化查询,附VBSCRIPT(ASP)和C#(ASP.NET)函数第1/2页

    最近因项目需要用ACCESS做数据库开发WEB项目 看论坛上还许多人问及ACCESS被注入的安全问题 许多人解决的方法仍然是用Replace替换特殊字符,然而这样做也并没有起到太大做用 今天我就把我用ACCESS参数化查询的一些方法和经验和大家分享 希望对大家有所启发,有写的不对的地方希望高手们多多指教 ASP.NET 用OleDbCommand的new OleDbParameter创建参数货查询 ASP用Command的CreateParameter 方法创建参数化查询 (SQL储存过程查询也

  • asp.net(C#)操作excel(上路篇)

    1.作业环境  开发环境:vs2005 /vs2008数据库:sql2005 excel:2003 首先 在vs加入com組件(当然也可以加入.net下的excel组件): 之后vs引用子目录会多出下面三个dll: 简单操作流程如下: 复制代码 代码如下: using Excel; // from bill example public void writeExcelAdvance(String outputFile) { string[,] myData = { { "车牌号", &

  • C#使用ADO.Net部件来访问Access数据库的方法

    数据库的访问是所有编程语言中最重要的部分,C#提供了ADO.Net部件用于对数据库进行访问.我们将从最简单易用的微软Access数据库入手讨论在C#中对数据库的访问. C#中的Connection对象和Command对象与Access类似,但在这里我们还将使用其另一个与RecordSet类似的被称作ADODataReader的对象,它负责处理与查询有关的RecordSet对象. 首先,必须使用微软的Access创建一个数据库.运行Access,创建一个数据库,但不要创建任何表(我们将在下面的程序

  • C#使用Ado.Net更新和添加数据到Excel表格的方法

    本文实例讲述了C#使用Ado.Net更新和添加数据到Excel表格的方法.分享给大家供大家参考.具体分析如下: 微软NET提供了一个交互的方法,通过使用ADO.NET与Microsoft Office程序.内置的OLEDB提供可以用来操纵Excel的.xls电子表格.您可以在Excel中创建一个命名的范围确定表名,我们还需要列标题,如果电子表格中不包含列标题,那么你就需要将它们添加. 如何在Excel中创建一个命名的范围? 随着电子表格打开,选择你希望包括数据查询,包括标题. 选择"插入&quo

  • ASP.net(c#)用类的思想实现插入数据到ACCESS例子

    昨天写了一半,一直没弄清楚当ACCESS数据库的连接代码写成类的时候路径该怎么写,搞了半天,还是用绝对路径解决了,似乎Server.MapPath没法在cs文件中使用. 要实现的功能如下: 尽量用类的思想来完成数据的插入,因为这个例子简单,所以我也就不多说什么.大家自己看代码,不懂的可以到论坛交流. 1.首先是ACCESS数据库的设计,数据库名:myData,表名:student 字段名称                    数据类型 sid                          

随机推荐