Create dynamic excel with C # In Asp.net

Source: Internet
Author: User

In asp.net, it is easy to create an Excel table and distribute it externally by the server. However, it is difficult to delete the embedded excel.exe process. Therefore, do not open the task manager to check whether the excel.exe process is still in the memory. Here I provide a solution, which provides two methods:

"Createexcelworkbook" (indicating creating an Excel Workbook) This method runs a stored procedure, returns a datareader, generates an Excel Workbook Based on the datareader, and saves it to the file system, create a "Download" connection, so that you can import the Excel table to the browser and directly download it to the machine.

The second method: generatecsvreport is essentially to do the same thing, just to save the CSV format of the file. Still import to excel, CSVCodeIt can solve the problem of a general piece in development: You have added multiple zeros in one column, and the CSV code can ensure zero and no null. (Note: multiple zero values in an Excel table cannot be saved)

The downloadable solution contains a valid class "spgen" that can run the stored procedure and return datareader. A method for removing files can be used to delete a specific time value. The main method shown below is createexcelworkbook.

Note: You must know that when running this page, you may need the Administrator permission to write Excel and CSV files in the file system of the websever server. The simplest way to solve this problem is to run this page in your own folder and include your own configuration file. Add the following element <identity impersonate = "true"... to the configuration file ".... You still need the write permission for the access control list (ACL) of the physical folder. Only the identity of the page running like this has the write permission. Finally, you need to set a com to connect to the Excel 9.0 or Excel 10 library,. net will generate an assembly for you. I believe that Microsoft has a connection on their office website and can download the initial accessories from Microsoft. (It may not be correct. I understand it as a. Net-oriented accessory installation)

<Identity impersonate = "true" username = "adminuser" Password = "adminpass"/>

Note that the following code block is used to clear 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 required, because osheet "," owb ", 'orng", and so on are also COM instances. We need

The releasecomobject method of the marshal class removes them from. 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 'round...

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. deleettings ["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 );

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

}

}

Below is the originalArticle

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 essential tially 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 shoshould 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. 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 specified Al 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 'round...

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. deleettings ["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 );

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

}

}

-Translation in a hurry. Please forgive me for any mistakes. Thank you for your advice. --- Xiao Xu

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.