Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Creative tools for business
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / ColdFusion Developer Center /

Working with spreadsheets in ColdFusion

by Ben Forta

Ben Forta
  • forta.com

Content

  • Example 1: Reading a spreadsheet and dumping the contents
  • Example 2: Working with formulas and formatting in spreadsheets
  • Where to go from here

Created

4 April 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
CFML ColdFusion database

Requirements

Prerequisite knowledge

Basic knowledge of CFML, databases, spreadsheets, and ColdFusion Builder.

User level

Intermediate

Required products

  • ColdFusion (Download trial)

Spreadsheets are key to just about all businesses and organizations, and ColdFusion developers have long sought a way to access and manipulate spreadsheet data programmatically. The truth is, ColdFusion has supported spreadsheet access for a while in a variety of ways, it's been possible to access Excel files from an ODBC driver, and it's been possible to generate these files using the CFReport tag as well as by generating HTML or CSV content and then setting the appropriate MIME type to force the browser to display the data using Excel.

But ColdFusion developers have been asking for more, greater and more control, and the ability to read and write specific parts of spreadsheet files.

Just like we did with the ColdFusion image manipulation functionality, spreadsheets in ColdFusion are manipulated using a tag or functions, or some combination thereof. The CFSPREADSHEET tag is used to read a sheet from a spreadsheet file (as a spreadsheet object, a query, a CSV string, or HTML), write sheets to XLS files, and add sheets to XLS files. This tag has over 30 supporting functions like SpreadsheetSetCellValue() , SpreadsheetAddRow() , and SpreadsheetSetCellFormula() allow for more granular spreadsheet manipulation, and can be used in conjunction with supporting functions like SpreadsheetNew() to create a new spreadsheet object, and SpreadsheetInfo() which returns title, subject, sheet names, last saved date and time, and more.

Example 1: Reading a spreadsheet and dumping the contents

Here are some of the examples I used at my presentations. This first example reads an entire spreadsheet as a query and dumps the contents:

<!--- Read spreadsheet ---> <cfspreadsheet action="read" src="Sales.xls" query="myQuery"> <cfdump var="#myQuery#">

This next example reads a specific cell on a specific sheet and returns it in a variable:

<!--- Read a spreadsheet cell ---> <cfspreadsheet action="read" src="Sales.xls" name="myVar" sheet="1" rows="C" columns="3"> <cfdump var="#myVar#">

CFSPREADSHEET is also used to write (or overwrite) a spreadsheet, as seen here:

<!--- Write spreadsheet ---> <cfspreadsheet action="write" overwrite="true" filename="Sales.xls" name="sObj" />

To update a specific cell, you need to read, update, and save, like this:

<!--- Read spreadsheet ---> <cfspreadsheet action="read" src="Sales.xls" name="sObj" /> <!--- Set cell value ---> <cfset spreadsheetSetCellValue(sObj, FORM.sales, FORM.row, FORM.col)> <!--- Write spreadsheet ---> <cfspreadsheet action="write" overwrite="true" filename="Sales.xls" name="sObj" />

This example uses form fields to specify the row, column, and value.

There's a lot more to it, but you get the idea. CFSPREADSHEET supports Excel and Open Office spreadsheet files.

Oh, and this one came up several times, so worth noting. Just like any other file access (for example, using CFFILE or CFIMAGE ), you'd not want concurrent access, and so you'd want to use CFLOCK calls when accessing and manipulating spreadsheet files, read locks when reading, exclusive locks when updating, using named locks (perhaps with the spreadsheet file name as the name).

Example 2: Working with formulas and formatting in spreadsheets

We'll start with a simple Application.cfc to define the data source needed for this app:

<cfcomponent> <cfset this.datasource="cfartgallery"> </cfcomponent>

Now to create a spreadsheet using a database query, use the following code:

<!--- Get data ---> <cfquery name="ArtOrders"> SELECT orderid, customerfirstname, customerlastname, total FROM orders ORDER BY orderid </cfquery> <!--- Save it ---> <cfspreadsheet action="write" query="ArtOrders" filename="Orders.xls" overwrite="true">

That's all it takes. The cfspreadsheet tag creates a spreadsheet populated with the retrieved data, using the query column names as column headers in the first spreadsheet row, and the data starting in the second row. Nice, huh?

But what if you want more control? What if you want to explicitly control data placement? What if you needed to provide row or column or cell level formatting? And what if you needed a total cell containing a formula to SUM the total column?

Here's a complete example showing you how to use the tag to control formulas and format in your spreadsheet:

<!--- Get data ---> <cfquery name="ArtOrders"> SELECT orderid, customerfirstname, customerlastname, total FROM orders ORDER BY orderid </cfquery> <!--- Create new spreadsheet ---> <cfset sObj=SpreadsheetNew()> <!--- Create header row ---> <cfset SpreadsheetAddRow(sObj, "Order,First Name,Last Name,Amount")> <cfset SpreadsheetFormatRow(sObj, {bold=TRUE, alignment="center"}, 1)> <!--- Add orders from query ---> <cfset SpreadsheetAddRows(sObj, ArtOrders)> <!--- Figure out row for formula, 2 after data ---> <cfset rowDataStart=2> <cfset rowDataEnd=ArtOrders.recordCount+1> <cfset rowTotal=rowDataEnd+2> <cfset totalFormula="SUM(D#rowDataStart#:D#rowDataEnd#)"> <!--- Add total formula ---> <cfset SpreadsheetSetCellValue(sObj, "TOTAL:", rowTotal, 3)> <cfset spreadsheetSetCellFormula(sObj, totalFormula, rowTotal, 4)> <!--- Format amount column as currency ---> <cfset SpreadsheetFormatColumn(sObj, {dataformat="$00000.00"}, 4)> <!--- Save it ---> <cfspreadsheet action="write" name="sObj" filename="Orders.xls" overwrite="true">

Once again, we start with a database query. Then, you use the SpreadsheetNew() function to create a new spreadsheet object.

The code then creates the header row. Use the SpreadsheetAddRow() function to add a specific row, the column headers (as no row number was specified, SpreadsheetAddRow() adds the row to the next free row, the first). Use the SpreadsheetFormatObject() function to format row 1, this function accepts a structure (which here is implicitly created inline).

Next comes the data. SpreadsheetAddRows() adds the entire query to the spreadsheet (again, as no row was specified the data gets added to the next free row).

Now for the formula that will total all orders. So as to not hard code the row, use a few <cfset> statements to calculate the first and last data row and the row for the total (second row after the end of the data, so leaving one empty row in between data and total). The formula can't be hard coded either, so instead of SUM(D2:D24) , the row variables are used to build the formula string dynamically. Use the SpreadsheetSetCellValue()function to add a title, and the SpreadsheetSetCellFormula() inserts the formula.

Next, the entire fourth column, containing the order amounts and the calculated total, is formatted to display as currency using the SpreadsheetFormatColumn() function.

All that is left to do then is to save the file using the cfspreadsheet tag.

The cfspreadsheet tag and its 30+ supporting functions can do lots more, but this should give you a taste of just what's possible using this innovative new feature.

Where to go from here

Next, check out my Adobe TV video (9:27 minute). Ben shows how ColdFusion 9 adds powerful and sophisticated spreadsheet support. Follow along as Ben Forta explains how to work with new and existing spreadsheets.

Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License+Adobe Commercial Rights

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License. Permissions beyond the scope of this license, pertaining to the examples of code included within this work are available at Adobe.

More Like This

  • Moving from Dreamweaver to ColdFusion Builder 2
  • A beginner's guide to using stored procedures with ColdFusion
  • Customizing the Eclipse IDE for robust ColdFusion application development
  • The United Way of America: A technical case study of rapid application development with ColdFusion 8, Ajax, and Flex
  • What's new in ColdFusion Builder 2
  • Accessing ColdFusion Services from Flex applications
  • Using DDX to unlock the potential of PDF manipulation in ColdFusion 8
  • Beyond HTML: Using Ajax, PDF, and more to create engaging applications with ColdFusion 8
  • Using ColdFusion 8 and Flex 3 to export visual components
  • Extending ColdFusion Builder

Tutorials & Samples

Tutorials

  • Using Axis2 web services with ColdFusion 10
  • Serving HTML5 videos with ColdFusion 10
  • HTML5 WebSockets and ColdFusion -- Part 2

Samples

ColdFusion Blogs

More
07/06/2012 Adobe ColdFusion 10 on CIO.com
06/22/2012 Elishia Dvorak Joins as ColdFusion Solution Consultant and Product Evangelist
06/19/2012 Outstanding contributions to the ColdFusion 10 and ColdFusion Builder 2.0.1 pre-release
06/18/2012 CF html to pdf service - consume from node.js using rest api

ColdFusion Cookbooks

More
04/01/2012 Send multiple mails with the adresses from database
07/27/2011 Passing a list with with STRING values
05/27/2011 AUTOMATED SANITIZED Resultset with ColdFusion
03/16/2011 Using Metadata To Add Static Variables to ColdFusion Components

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement