Introduction
One of the great things about running an ASP Web site where visitors regularly contribute articles is that, in reading/editing those article submissions, I end up learning a lot of new things! Last week Bret Hern submitted a beautiful article on using Charting with Office Web Components. After poking around Microsoft's site some, I found rather terse, technical documentation on these nifty components and soon discovered that these components can also be used to create Excel spreadsheets via ASP code! These spreadsheets can then be saved as an Excel file for the user to download.
In this article we will look at using the Office Web Components (OWC) to create an Excel spreadsheet via ASP code based on the results from a database query! All of this complexity is encapsulated in a (rather basic) class. In the upcoming weeks I plan to expound on this class. Currently it just dumps the contents of a Recordset into a spreadsheet, but in future weeks I'd like to show how to add nifty formatting, apply formulas, pivot tables, and all that other jazzy stuff.
| Licensing Issues |
|---|
| Microsoft has some pretty strict licensing issues on using Office Web Components in the Internet-world (as well as on an intranet). Before you begin using Office Web Components on your Web site be sure to read Microsoft's Licensing Agreement for OWCs. |
Getting Started
To get started using Office Web Components you must have (at minimum) the Office Web Components section of Office 2000 installed on the Web server. (If you are wanting to create Excel spreadsheets and graphs without requiring Excel's presence on the Web server be sure to check out SoftArtisan's ExcelWriter component.) (For more on OWC requirements and installation information check out: Requirements for Office Web Components!)
Creating a Spreadsheet
In this article we will look only at the basics of creating a spreadsheet, setting various cell values, and saving the spreadsheet to disk. In future articles we will look at prettying up the display and working with some of the more advanced features...
Since the spreadsheet aspect of the Office Web Components is a simple COM object, you can create an instance of the spreadsheet component through your ASP page just as you would create an instance of any other COM component:
'Create an instance of the Spreadsheet component from OWC |
Simple enough. Once you have a Spreadsheet object to work with you can set the values of the spreadsheet's cells using the Cells property of the Spreadsheet object like so:
objSpreadsheet.Cells(Row, Column).Value = SomeValue |
Finally, to save the Spreadsheet as an Excel file you must use the Export method of the Worksheet object. (The ActiveSheet property of the Spreadsheet object returns a valid Worksheet object instance.) The Export method expects two parameters: a full physical file name and an SheetExportActionEnum constant. The file name parameter specifies the specific location to save the Excel spreadsheet; the export action indicates if the file should be saved to disk or piped directly to Excel. Since we are running all of this code on the server-side, if we try to pipe the spreadsheet contents directly to Excel, we will be trying to open Excel on the Web server - not what we want to do. In fact, this setting is only useful if you are using the Spreadsheet object as an ActiveX control, since then it will be executing on the client's machine as opposed to on the Web server. Therefore, when using the Export method in server-side script, always specify a value of 0 for the export action, which indicates to the Export method to simply save the spreadsheet to disk and to not try to pipe the contents straight to Excel.
objSpreadsheet.ActiveSheet.Export("C:\Inetpub\wwwroot\FooBar.xls", 0) |
Keep in mind that the IUSR_machinename account must have Write permissions on the directory that you wish to write the Excel file to. If the IUSR_machinename account has inadequate permissions you will receive an error when trying to use the Export method... (Check out this FAQ for more information...)
Creating the Class
I chose to encapsulate the complexity of creating/populating/saving a spreadsheet into a VBScript class. That means that you will need VBScript version 5.0 or higher installed on your Web server. To find out what version of VBScript you are currently using, check out: Determining the Server-Side Scripting Language and Version. Also, for more information on the ins and outs of classes be sure to read Mark Lidstone's excellent article: Using Classes within VBScript.
Our class contains three private properties: objSpreadsheet, iColOffset, and iRowOffset. In the Class_Initialize() event handler, an instance of the Spreadsheet COM component is instantiated and referenced by objSpreadsheet; iColOffset and iRowOffset, which specify the how many columns over and rows down we should start inserting the database results, are initialized to values of 2.
|
Next, two Property Let constructs are defined to allow users of this class to programmatically set the row and column offsets. These Property Let statements ensure that the offsets attempted to be set are greater than zero.
|
Creating the Methods for the ExcelGen Class
Only two methods are needed for our class. The first one, GenerateWorksheet, accepts a single parameter: a populated Recordset object. This method then loops through the Recordset, transferring its contents to objSpreadsheet's Cells. Note that both the data from the Recordset and the names of the columns in the Recordset are outputted to the Excel spreadsheet.
|
Our last method, SaveWorksheet, accepts a single parameter, strFileName, which specifies the location to save the spreadsheet. This method returns a Boolean value: True if the file is saved successfully, False otherwise. Recall that exporting the Spreadsheet object to a physical Excel file can fail if the IUSR_machinename account has inadequate permissions.
|
Using the ExcelGen Class from an ASP Page
Now that we've looked at the contents of our class, let's examine how to use it through an ASP page to create a spreadsheet containing the contents of a Recordset! It is highly recommended that you place the ExcelGen class in an include file and then use a server-side include on those ASP pages that need to utilize the class's functionality. (To learn more about server-side includes be sure to read: The Low-Down on #include.) For this example we'll assume that the ExcelGen class has been placed in the file /scripts/ExcelGen.class.asp.
To use this class, then, we'll use a server-side include to import the contents of /scripts/ExcelGen.class.asp. Next, we'll create an instance of the class using the New keyword. Once we've created and populated a Recordset, we can call the .SaveWorksheet method to dump the Recordset's contents into an Excel spreadsheet. Finally, we need to save the contents of the spreadsheet using the .SaveWorksheet method.
|
If the spreadsheet is saved successfully the user is presented with a hyperlink to download the Excel file.
Conclusion / Caveats
One annoying thing with the ExcelGen class is that a user must go through a two-phase step to view the contents of a Recordset through an Excel file. First, he must visit an ASP page that creates the Recordset; next, he must click on the link to the Excel file. This is a pain and something I plan on fixing in the next article on this topic (which will serve, basically, as an enhancement to the ExcelGen class).
One major concern that should also be quickly apparent is that in the above example the Excel spreadsheet is always saved to the same file. Urg. This is bad since multiple users will be trying to access the same file and, most likely, they would be running different kinds of database queries producing varrying output. One approach is to create a unique file for every user visiting the page... but then how to we clean up old spreadsheets? We'll examine this topic in more detail in a future article...
In the mean time, play with the code here, create your own spreadsheets, and poke around the Microsoft documentation. Happy Programming!
discuss this topic to forum
