TweetFollow Us on Twitter

Chart Generation Volume Number: 17 (2001)
Issue Number: 3
Column Tag: Programming Techniques

Chart Generation with AppleScript & Excel

By Rich Allen
Edited by Cal Simone

A friend of mine likes to say "everything is easy once you know how", Updating an Excel spreadsheet and generating an accompanying chart is easy using a little AppleScript, and Microsoft Excel, once you know how!

People like charts. Charts are an easy way of seeing a lot of data and understanding it with a quick glance. Using AppleScript to update an existing workbook, a simple VisualBasic macro for exporting a chart as a JPEG file and the iDo Script Scheduler included with OS 9 is all you need to create a regularly updated chart. This article will explain how to

  • Use AppleScript to parse a data file for required values
  • Transmit those values to Excel
  • Tell Excel to export a chart as a JPEG file for use as part of a web page
  • How to setup iDo so the chart is updated regularly

A note on conventions used in the AppleScript source listing; those words that have an underline are application keywords. These terms have a specific meaning to either the enclosing tell block or to AppleScript itself. See the preferences panel of your script editor for implementing this option.

First let's look at using AppleScript to open a file of raw data and parse out the values that we really want. For our raw data file, we will use a tab-delimited text file as shown in Listing 1.

Listing 1: Sample raw data

Date   Hour   PhoneNum   Type   Members   Peg   Busy   Usage
12/20/00   09   5551234   DNH   3   7   0   17
12/20/00   09   5552345   DNH   4   9   0   34
12/20/00   09   5553456   DNH   2   1   0   3
12/20/00   09   5554488   DNH   4   5   0   6

For this project, we require the values under the headings labeled "Date", "Hour", "Peg" (number of telephone calls), and "Usage" (connect time of all calls) for telephone number 5554488. We will assume that this raw file is updated once each hour, although we will want to verify this, and that our chart will track peg values versa usage value count on an hourly basis. The Excel workbook will be pre-built with two worksheets; one containing the chart (chart) and another with the values that feed that chart (data). See Figures 1 and 2 for examples of these worksheets.


Figure 1. Sample chart output.


Figure 2. Property declaration.

OK, let's start writing a script! The script will use three properties, values that will be used throughout the script. These properties designate the path to the folder containing our files, the name of the raw data file, and the telephone number to find. See Listing 2.

Listing 2: Sample of worksheet data

property folderPath : "MacHD:Desktop Folder:MacTech:"
property fileName : "rawdata"
property phoneNumber : "5554488"

It is always a good idea to have a try block around scripting statements to catch any error that may arise. The main portion of the script, Listing 3, is completely enclosed in a single try block. Any error encountered will be handled by the on error section. For example, if the raw data file can not be found when AppleScript tries to open it, an error will occur, passing control to the on error routine.

The script starts by setting fileRef to an empty string. By doing this, if an error does occur, the error handler will be able to determine if the data file is open, if so, closing it. If the error routine is invoked and fileRef is the empty string, then the error was generated while attempting to open the file thus there will be no need to execute the close access statement.

Next the script will attempt to open the raw data file, concatenating the folderPath and fileName properties into a single string as input for the open for access statement and assigning the resulting file reference number to the variable fileRef. From this point on, we can access data from the file by referring to the fileRef variable. We know that the data file is tab-delimited (a tab character seperates each value in the file), so next, the script is set to use the tab character as its text item delimiter. (Normally AppleScript's text item delimiter is set to an empty character (""). Since we already know that each value of interest per line is separated by the tab character, by setting AppleScript's text item delimiters to a tab we can easily refer to any value by its position.)

The sample data file contains eight items per line; in this case the date, the hour, phone number, phone number type, number of members associated with the phone number, a peg count, number of busies and the usage. The variable num will be set to the empty string and will later be set to the telephone number from each line that is read from the data file and then compared to the property phoneNumber to determine a positive match.

At this point the script is ready to start reading each line of the data file until it finds a match of the phone number read and the desired number. Reading a line of the data file is done with the standard read statement; reading from the current file position until the next encountered return character. If the two telephone numbers do not match, the next line is read and phone numbers compared. If the desired phone number is not found before the end of the file (eof) is reached then an error will be created by AppleScript and handled by the on error portion of the run handler, otherwise the close statement will be executed to close the data file.

Listing 3: The run handler

try
   set oldDelimiter to AppleScript's text item delimiters
   set AppleScript's text item delimiters to tab
   set fileRef to ""
   set fileRef to open for access (folderPath & fileName)
   set num to ""
   repeat until num is phoneNumber
      set dLine to read fileRef before return
      set num to text item 3 of dLine
      if (phoneNumber is num) then
         UpdateWorkbook(dLine)
      end if
   end repeat
   close access fileRef
   set AppleScript's text item delimiters to oldDelimiter
on error errMsg number errNum
   if fileRef is not "" then
      close access fileRef
   end if
   set AppleScript's text item delimiters to oldDelimiter
end try

Once a match has been found, the UpdateWorkbook handler (Listing 4) is called. (A handler is basically equivalent to a subroutine.) The script starts with a tell statement that will direct any statements following towards Excel. For any statement within the tell block that are not directly understood by Excel, those statements will be handled by AppleScript itself (e.g. if).

The first statement to Excel will open the required workbook by combining two of the properties set initially and adding the ".xls" suffix to match the exact file name and path of the required workbook. Since the workbook contains more then one worksheet (chart and data), the script selects the data worksheet to assure the values from the raw data file will be inserted into the proper cells.

For this workbook and chart we are tracking 24 hours of data. The data worksheet contains a header in the first row with the following 24 rows containing the last 24 hours worth of data. Refer back to Figure 2 for an example.

We will want to verify that the raw data we have read is new before we update the worksheet. By comparing the hour from the line of raw data with the last hour on the data worksheet (cell B25), we can be sure that the raw data has been changed.

Since we want our chart to show peg versa usage information on an hourly basis, we will want to drop the oldest hour's data from our chart and add the newest data. By copying the last 23 hours data values (rows 3 through 25) and then pasting those values into the first 23 hours data (rows 2 through 24), the script has effectively dropped the oldest hour. (Note that the copyobject keyword, used here, comes from Excel's Custom Suite - unfortunately Excel does not have the standard copy verb as many other applications do.) Rows 24 and 25 are now the same. To add the newest data, the script will simply set the new values in row 25, overwriting the extraneous values.

Now that all the values have been updated, it's time to export a copy of the chart for use on the web page. Excel has an export function using VisualBasic that can accomplish this (the macro is contained within the workbook). We will not delve into Excel VisualBasic macros in this article but will show the macro we're using here in Listing 5. AppleScript uses the evaluate statement to communicate with Excel to run the macro. Be sure to note the syntax here, evaluate requires the file name of the workbook concatenated with the name of the macro with the exclamation point character separating them.

The last job for the UpdateWorkbook handler is to save the changes made to the workbook and close the workbook file.

Listing 4: The UpdateWorkbook handler

on UpdateWorkbook(dataLine)
   tell application "Microsoft Excel"
      open (folderPath & phoneNumber & ".xls")
      select sheet "data"
      if (text item 2 of dataLine != value of cell "$B$25") then
         select range ("$A$3:$D$25")
         CopyObject selection
         select range ("$A$2:$D$24")
         paste
         set value of cell "$A$25" to text item 1 of dataLine
         set value of cell "$B$25" to text item 2 of dataLine
         set value of cell "$C$25" to text item 6 of dataLine
         set value of cell "$D$25" to text item 8 of dataLine
         evaluate (phoneNumber & ".xls!ExportChart()")
         close ActiveWorkbook saving yes
      end if
   end tell
end UpdateWorkbook

Listing 5: VisualBasic macro to export chart as JPG

Sub ExportChart()
Charts("Chart").Export _
    FileName:="pb0:Desktop Folder:MacTech:5554488.jpg"
End Sub

Each time the script is run it will update the workbook and export a new chart for use on a web page. This script does not provide a method of performing this task on a regular basis so how do we get it to run on a schedule? One solution is to use the iDo Script Scheduler that is included with the Mac OS. If it is not already in your control panels folder, you will find it on the Mac OS 9 CD in the CD Extras folder in the AppleScript Extras folder.

Open the iDo Script Scheduler control panel and click on the New button. Give this event a name, set the trigger to "repeating", and select the start time and date. All that is left is to click the Choose button, select the script (which we've saved as a compiled script), and save the newly created event. Your chart will now be updated every hour at the specified time. See Figure 3 for an example of the iDo event.


Figure 3. iDo event.

Although this is a short script with only limited error checking, it does demonstrate the ease of integrating AppleScript with Microsoft Excel to create charts suitable for use on any web page!

My friend also has another thing he likes to say, "Now that I know how, it's easy!"


Rich Allen currently works for a local telephone company in Alaska in the traffic-engineering department. He has held a variety of telecommunications positions since 1984 and has designed a number of Macintosh based data systems. His email address is g3pb@alaska.net.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.