Welcome!

You will be redirected in 30 seconds or close now.

ColdFusion Authors: Yakov Fain, Jeremy Geelan, Maureen O'Gara, Nancy Y. Nee, Tad Anderson

Related Topics: ColdFusion

ColdFusion: Article

Excel's Web Query

Excel's Web Query

In today's world of e-commerce, simply viewing data in a Web browser is rarely enough. Clients constantly demand reporting, charting, graphing, and analysis of complex data. Although Macromedia has made great strides in this direction by incorporating graphing capabilities (the new CFGRAPH) and access to a reporting engine (CFREPORT), these are all server-side solutions. A simple request for a new chart can send developers scrambling. Wouldn't it be great if end users could manipulate and analyze data themselves, using a powerful suite of tools that they're already familiar with!

Since its inception in 1988, Microsoft Excel has grown to become the Swiss Army knife of data analysis. While not always the best tool for the job, users tend to make it do just about anything. Nontechnical people can easily store inventories, financial records, even data best suited for a relational database. Excel then gives them the power to twist this data into any imaginable chart or report.

Getting the Data
With so many users familiar with the Excel interface, it would be useful to push live data into a spreadsheet, leaving the actual manipulation to the discretion of the user. But how do we feed live data into Excel from a Web server? Supply the users with tab delimited files? Excel has no problems there, but the user would have to download a new file every time the data changes. Copy and paste? Far too tedious. Office XP promises powerful new integration with the Web-based XML data.

Fortunately, an extremely powerful method of data acquisition has been around since Excel 97. The woefully underpublicized Web query allows Excel to fetch data from an HTML table anywhere on the Internet. This data is dropped directly into a worksheet, and behaves as if the user entered it manually. A simple click of the mouse instructs Excel to open an HTTP connection and get the latest data.

For this article, I've set up a special ColdFusion page that when given a part number generates a table of inventory data (see Figure 1). Excel can also handle preformatted text, blocked in the PRE tag.

For Excel to feed off this data, we must instruct the spreadsheet exactly where to find the table. From the Data menu, click Get External Data > New Web Query. A dialog box will then walk you through the steps necessary to import data. Excel 97 users will need to install Microsoft Query, included on the Microsoft Office 97 CD.

There are plenty of advanced options in the new Web Query window, and I'll let you explore them on your own. Once you tell Excel where to find its data, simply click OK, and watch the magic unfold. Excel will open a connection and parse the HTML file. Any formatting, whether HTML- or CSS-based, will be preserved (to a degree), so you can reliably set fonts, color, borders, etc.

Once the download is complete, right click on any imported cell and you'll see a new choice on the context menu. "Refresh Data" instructs Excel to go out and fetch the latest data, dropping it back into the table. There's also a Refresh Data icon on the toolbar (a red exclamation mark) that refreshes all the Web queries in the document. If your HTML table has changed sizes, Excel is even smart enough to expand or contract its range of cells to accommodate the change without overwriting other content on the sheet.

Notice that you no longer have to tell Excel where to get its data. The URL and any configuration parameters have been embedded into the document. You can convert a Web query back to plain data by right-clicking on the cell, choosing Data Range Properties, and clearing the "Save query definition" checkbox.

Excel Extensions
When composing the live Web page, Excel provides a few extensions to normal HTML. These extensions, invisible when viewing the page in a Web browser, provide extra functionality when the document is interpreted by Excel. We'll cover two of them here: filters and formulas. Additional extensions allow you to properly format data and work with PivotTables.

The first extension allows the user to quickly filter data based on a set of parameters. This applies if you have a row of column headers. In our case, the following code generates a header:

<TR>
<TD Filter="ALL">Warehouse Location</td>
<TD Filter="ALL">Quantity In Stock</td>
</tr>
By supplying the "filter" attribute, Excel will generate a drop-down menu of filter options (see Figure 2). The user can then choose to filter for a particular value, the top 10 values, etc. All of this is accomplished using Excel's built-in AutoFilter feature. Note that for filtering to work correctly, Excel needs to use HTML formatting. This is an option in the new Web Query window.

Excel also allows you to build a formula in a cell. For instance, to find the total stock of a given item across 10 warehouses, we could use:

<TD Formula="=Sum(B2:B11)"></td>
In this case, Excel will sum the values of the range B2 to B11 and display the result in the cell. If the user decides to change one of the values, the sum will update to show the change. Although not required in a formula attribute, the equal sign inside the quotes matches Excel's function notation.

It's important to remember that a user can drop the results of a Web query anywhere on a spreadsheet. It may seem like summing the results of cells B2 to B11 could be unreliable. What happens if the user puts the query at cell D35? Fortunately, Excel corrects this. When the formula appears on the sheet, it will use the data relative to your table. Therefore, if you specify cell A1 in a formula, it will always represent the upper-left corner of the HTML table, regardless of where the query was placed on the spreadsheet.

IQY Files
Although Web queries are obviously powerful, they still require a degree of configuration on the part of the user. Do you really want people to have to worry about URLs and query parameters? Luckily, Microsoft has devised a standard for defining a Web query. An IQY file, a simple text file, allows system administrators to package a query for distribution. The user can then run the query from the Data menu (click Get External Data > Run Saved Query). Excel 2000 and XP users can even double-click an IQY file and Excel will open a new spreadsheet and import the data. Unfortunately, this feature was left out of Excel 97.

To understand IQY files, let's look at a simple example:

WEB
1
http://www.myserver.com/inventory_
grid.cfm?partnum=10
The first two lines of an IQY file are easy, in fact, they're always the same. The first instructs Excel how it will import the data. Notice that "WEB" is uppercase. The second line represents the version of the IQY definition. Fortunately, Microsoft has created only one version, so we'll stick with 1. Running this IQY file will produce the same results as manually configuring a Web query. In the previous example, Excel imported and displayed inventory data for a particular part. What if we don't want to limit the user to a specific part? Let's consider a more sophisticated IQY file:

WEB
1
http://www.myserver.com/inventory_
grid.cfm?partnum=["Part Number","Please enter a part number:"]
Now the user will be prompted for a part number to display. The first argument ("Part Number") is a descriptive name of the variable. The second argument is displayed as a prompt when the user loads the data (see Figure 3). The user's entry is passed to the Web server as a URL parameter. To pass multiple URL variables, simply separate them by ampersands, as you would an ordinary URL:

WEB
1
http://www.myserver.com/inventory_
grid.cfm?partnum=["Part Number","Please enter a part number:"]
&warehouse= ["Warehouse ID",
"Please enter a warehouse ID:"]
If, on the other hand, you want to pass data as form variables, simply place the prompt on the fourth line:

WEB
1
http://www.myserver.com/inventory_grid.cfm
partnum=["Part Number","Please enter a part number:"]
Multiple form variables are delineated by ampersands, much like URL parameters:

WEB
1
http://www.myserver.com/inventory_grid.cfm
partnum=["Part Number","Please enter a part number:"]
&warehouse=["Warehouse ID","Please enter a warehouse ID:"]
There are a number of miscellaneous options you can specify on subsequent lines, such as "Selection=<table name>", which controls which table on the HTML page gets parsed. The best way to explore these extra parameters is to build a Web query in Excel, save it to an IQY file, and examine the results. Individual options may or may not be compatible with older versions of Excel, so be sure to test your files before distributing them!

Dynamic IQY Files ,br> Although it's fairly simple to write an IQY file and place it on the company intranet for users to download, there are times where it would be handy to generate IQY files on the fly. For instance, a Web page that displays inventory on a particular part could have a link "Connect to Excel". This could download a static IQY file, although an administrator would have to make sure that an individual IQY file exists for every part in the database.

If we could pass the part number in as a URL variable, we could write the following file, saving it as "connect_to_excel.cfm":

WEB
1
http://www.myserver.com/inventory_grid.cfm?partnum=
<CFOUTPUT>#URL.PartNumber#</cfoutput>
When users click the link to this CFM page, however, their Web browsers will likely display the file on screen as plain text. They would then have to save the file with an IQY extension, and then open it in Excel.

There are two distinct problems with this solution. First, the file is displayed on screen and the user must know to save it locally. To remedy this problem, we'll employ the CFCONTENT tag, which changes the MIME type of the document. Originally created to handle e-mail, the MIME type instructs the browser how to display a document. The default type for Web pages is "text/html".

In this case, we'll utilize the "application/octet-stream" type that is reserved for files the browser can't display, such as binary data. This will force a "Save As" dialog box to appear. The following CFML will return the file with the new MIME type:

<CFCONTENT type="application/octet-stream">
WEB
1
http://www.myserver.com/inventory_grid.cfm?partnum=
<CFOUTPUT>#URL.PartNumber#</cfoutput>
Notice that the CFCONTENT and the "WEB" specification are on the same line. If we were to put a linefeed between the two, an empty line would appear in the resulting file and confuse Excel. Once the "Save As" dialog box appears, the file will be saved as "link_to_excel.cfm". Ideally, the file should come with an IQY extension, ready to be loaded into Excel.

Instead of directly linking to connect_to_excel.cfm (our dynamic IQY file), we'll employ the following trick:

<A HREF="http://www.myserver.com/connect_to_excel.cfm
/DynamicLink.iqy">

ColdFusion is smart enough to process connect_ to_excel.cfm, but the browser sees the file as DynamicLink.iqy.

For More Information
Unfortunately, documentation for Web queries is hard to find, especially regarding the IQY file syntax. Microsoft published the Web Connectivity Kit for Excel 97, which, to my knowledge, was its last official publication on the matter, but there is another excellent resource at www.15seconds.com/issue/991021.htm. Microsoft also includes some great examples used to fetch stock reports.

By feeding live data into Excel, you can empower users to manipulate data on the client side without requiring constant changes to the Web application. They can then use Excel's capabilities to analyze and chart data. By using Web queries, users can effortlessly update their data.

More Stories By Norman Elton

Norman Elton is a computer science student and the ColdFusion guru at the College of William & Mary in Williamsburg, Virginia.

Comments (1)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


IoT & Smart Cities Stories
As the fourth industrial revolution continues to march forward, key questions remain related to the protection of software, cloud, AI, and automation intellectual property. Recent developments in Supreme Court and lower court case law will be reviewed to explain the intricacies of what inventions are eligible for patent protection, how copyright law may be used to protect application programming interfaces (APIs), and the extent to which trademark and trade secret law may have expanded relev...
When Enterprises started adopting Hadoop-based Big Data environments over the last ten years, they were mainly on-premise deployments. Organizations would spin up and manage large Hadoop clusters, where they would funnel exabytes or petabytes of unstructured data.However, over the last few years the economics of maintaining this enormous infrastructure compared with the elastic scalability of viable cloud options has changed this equation. The growth of cloud storage, cloud-managed big data e...
Your applications have evolved, your computing needs are changing, and your servers have become more and more dense. But your data center hasn't changed so you can't get the benefits of cheaper, better, smaller, faster... until now. Colovore is Silicon Valley's premier provider of high-density colocation solutions that are a perfect fit for companies operating modern, high-performance hardware. No other Bay Area colo provider can match our density, operating efficiency, and ease of scalability.
The Japan External Trade Organization (JETRO) is a non-profit organization that provides business support services to companies expanding to Japan. With the support of JETRO's dedicated staff, clients can incorporate their business; receive visa, immigration, and HR support; find dedicated office space; identify local government subsidies; get tailored market studies; and more.
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
In an age of borderless networks, security for the cloud and security for the corporate network can no longer be separated. Security teams are now presented with the challenge of monitoring and controlling access to these cloud environments, at the same time that developers quickly spin up new cloud instances and executives push forwards new initiatives. The vulnerabilities created by migration to the cloud, such as misconfigurations and compromised credentials, require that security teams t...
AI and machine learning disruption for Enterprises started happening in the areas such as IT operations management (ITOPs) and Cloud management and SaaS apps. In 2019 CIOs will see disruptive solutions for Cloud & Devops, AI/ML driven IT Ops and Cloud Ops. Customers want AI-driven multi-cloud operations for monitoring, detection, prevention of disruptions. Disruptions cause revenue loss, unhappy users, impacts brand reputation etc.
Today's workforce is trading their cubicles and corporate desktops in favor of an any-location, any-device work style. And as digital natives make up more and more of the modern workforce, the appetite for user-friendly, cloud-based services grows. The center of work is shifting to the user and to the cloud. But managing a proliferation of SaaS, web, and mobile apps running on any number of clouds and devices is unwieldy and increases security risks. Steve Wilson, Citrix Vice President of Cloud,...
Cloud computing, big data and AI provide a new impetus and urgency to traditional enterprises to become digitally transformed businesses as they face disruption from new players who leverage technology to foster new business models. Traditionally, enterprises focused on digitizing processes and transactions. The incumbents can also be disruptors by leveraging AI for data-driven insights and innovate at scale on Cloud platform. They need to uncover the power of ERP/SAP using Cloud, AI and Big dat...
The graph represents a network of 1,329 Twitter users whose recent tweets contained "#DevOps", or who were replied to or mentioned in those tweets, taken from a data set limited to a maximum of 18,000 tweets. The network was obtained from Twitter on Thursday, 10 January 2019 at 23:50 UTC. The tweets in the network were tweeted over the 7-hour, 6-minute period from Thursday, 10 January 2019 at 16:29 UTC to Thursday, 10 January 2019 at 23:36 UTC. Additional tweets that were mentioned in this...