• The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
Menu
  • The Four Hundred
  • Subscribe
  • Media Kit
  • Contributors
  • About Us
  • Contact
  • Create Excel Spreadsheets From DB2 Data With PHPExcel

    February 10, 2015 Bruce Guetzkow

    Note: The code accompanying this article is available for download here.

    It is amazing that so many users manually key from a report into a spreadsheet for further analysis. PHPExcel is a tool that you can use to write directly to a spreadsheet for them. Here are the steps that you need to take to install and create a simple spreadsheet from DB2 data using PHPExcel.

    Getting Started

    The following are requirements to use PHPExcel on Power Systems on IBM i:

    • Zend Server must be installed and running
    • PHPExcel must be downloaded and installed

    For the purposes of this article, I assume that you have already installed Zend Server. If not, see this link for Zend Server Installation for IBM i and/or use a search engine. Although it is always a good idea to be reasonably current on software versions, it is not necessary to have the latest version of Zend Server installed. (I have used PHPExcel with version 5.0.x of Zend Server.)

    Installing PHPExcel is very simple. Go to https://phpexcel.codeplex.com/ and download the ZIP file to the folder of your choice and unzip it with your favorite archive tool. The ZIP file contains the following folders and files:

    • Classes–Contains the PHPExcel code
    • Documentation–Contains all of the current documentation
    • Examples–Contains examples of how to use PHPExcel
    • changelog.txt–Contains a list of all of the updates to the product
    • install.txt–Contains instructions on how to install PHPExcel (be sure to read this)
    • license.txt–Contains the licensing information

    Copy the “Classes” folder into the IFS. You can put this folder anywhere you like. If you plan to use PHPExcel with a Web application you may wish to put it under your Web root folder. The examples that I will show all call the PHP scripts from a CL program, but I will show it installed within a Web root so that you will have the option to use it from the Web as well.

    That’s it! You’re ready to start using PHPExcel.

    Your First Script

    To begin your PHP script there are some basic housekeeping tasks to perform. First, you need to reference the functions provided with PHPExcel:

    // Require PHPExcel Classes
    require_once '/www/zendsvr/htdocs/Classes/PHPExcel/PHPExcel.php';
    

    Next you can retrieve any parameters that you might wish to pass to your script. In this example I am attempting to retrieve “year” and “month” parameters. If the script is called from a browser URL they will be available from the $_GET array. If the script is called from a CL program they will be available from the arguments array (the first argument–$argv[0]–is always the name of the script being executed):

    // Get Parms
    $year = ( $_GET['year'] ? $_GET['year'] : $argv[1] );
    $month = ( $_GET['month'] ? $_GET['month'] : $argv[2] );
    

    The last bit of housekeeping is to connect to the IBM i database:

    //Set the database
    $database = "SYSTEMNAME";
    //Using a username and password of *Blanks will use the default use of QTMHHTTP
    $username = "";
    $password = "";
    
    //The following line sets db2 options.  Library list can have multiple libraries 
    separated by a space.
    $options = array("i5_libl" => "LIBRARYA LIBRARYB", "i5_naming" =>
    DB2_I5_NAMING_ON);
    //Connect to db2 database
    $conn = db2_connect($database, $username, $password, $options);
    if(!$conn)
    {
    	die("Connection Error");
    }
    

    Now you can start to use PHPExcel. Create a spreadsheet object and assign whatever attributes you feel are appropriate. I won’t go into details for now, but here are some examples:

    //Setup PHPExcel object and document properties
    $objPHPExcel = new PHPExcel();
    $title = 'My Report';
    $objPHPExcel->getProperties()->setCreator("Bruce Guetzkow")
    				->setLastModifiedBy("Bruce Guetzkow")
    				->setTitle($title)
    				->setSubject($title)
    				->setDescription($title)
    				->setKeywords($title)
    				->setCategory("report");
    

    You need to set the active worksheet that you will be writing to. As always, PHP uses zero-based elements, so the first worksheet is element 0:

    //Set active sheet index
    $objPHPExcel->setActiveSheetIndex(0);
    

    Load Your DB2 Data

    Let’s add some data to the spreadsheet. Begin by placing a “select” SQL statement into a variable:

    // Define the SQL Statement
    $sqlstmt ="select fielda, fieldb, fieldc
                  from myfile
                 where datayear = $year and datamonth = $month";
    

    The SQL statement must then be prepared:

    // Prepare the SQL Statement
    $stmt = db2_prepare($conn, $sqlstmt);
    if(!$stmt)
    {
       	$error = db2_stmt_errormsg();
       	die( "Error occured on prepare. " . $error);
    }
    

    You are now ready to execute the statement:

    //Execute the SQL Statement
    $result = db2_execute($stmt);
    if(!$result)
    {
       	$error = db2_stmt_errormsg();
       	die("Error occured on execute. " . $error);
    }
    

    PHPExcel provides a simple way to load an entire row retrieved by your SQL statement to a spreadsheet row in a single step. You can also load individual cells, but this is a great way to get started:

    // Load Data to Spreadsheet
    $currRow = 0;
    while ($row = db2_fetch_array($stmt)) {
    	$currRow++;
    	$objPHPExcel->getActiveSheet()->fromArray($row, ' ', "A$currRow");
    }
    

    At this point the spreadsheet is still contained in the PHPExcel object. It’s now time to write this to the IFS:

    // Write Spreadsheet
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
    $objWriter->save("/myfolder/mySpreadsheet.xlsx");
    

    Try It For Yourself

    You should now be able to open your spreadsheet and see rows of data extracted from a DB2 file. Of course all you have is the data–no headings, totals, formulas, or formatting. Next time we’ll tackle a few attributes that will give your spreadsheet a bit more pizazz.

    As you might have already guessed, the Documentation folder that you extracted earlier contains instructions on spicing up your document. Now that you have the basics, go ahead and experiment with other settings and surprise yourself.

    Bruce Guetzkow, an independent IBM i programming consultant with GmanTech Consulting in Southeastern Wisconsin, is a firm believer in practical programming. For nearly 30 years he has developed applications for IBM systems from mainframe to System/36 to Power Systems on IBM i. You can follow him on Twitter (@gmantechi) or catch him at a meeting of the Wisconsin Midrange Computer Professional Association (WMCPA) in Milwaukee. Send your questions or comments for Bruce to Ted Holt via the IT Jungle Contact page.

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Tags:

    Sponsored by
    WorksRight Software

    Do you need area code information?
    Do you need ZIP Code information?
    Do you need ZIP+4 information?
    Do you need city name information?
    Do you need county information?
    Do you need a nearest dealer locator system?

    We can HELP! We have affordable AS/400 software and data to do all of the above. Whether you need a simple city name retrieval system or a sophisticated CASS postal coding system, we have it for you!

    The ZIP/CITY system is based on 5-digit ZIP Codes. You can retrieve city names, state names, county names, area codes, time zones, latitude, longitude, and more just by knowing the ZIP Code. We supply information on all the latest area code changes. A nearest dealer locator function is also included. ZIP/CITY includes software, data, monthly updates, and unlimited support. The cost is $495 per year.

    PER/ZIP4 is a sophisticated CASS certified postal coding system for assigning ZIP Codes, ZIP+4, carrier route, and delivery point codes. PER/ZIP4 also provides county names and FIPS codes. PER/ZIP4 can be used interactively, in batch, and with callable programs. PER/ZIP4 includes software, data, monthly updates, and unlimited support. The cost is $3,900 for the first year, and $1,950 for renewal.

    Just call us and we’ll arrange for 30 days FREE use of either ZIP/CITY or PER/ZIP4.

    WorksRight Software, Inc.
    Phone: 601-856-8337
    Fax: 601-856-9432
    Email: software@worksright.com
    Website: www.worksright.com

    Share this:

    • Reddit
    • Facebook
    • LinkedIn
    • Twitter
    • Email

    Sponsored Links

    Northeast User Groups Conference:  25th Annual Conference, March 30 - April 1, Framingham, MA
    Profound Logic Software:  Reach Your Modernization Goals. Register for the February 25 Webinar now!
    System i Developer:  Upgrade your skills at the RPG & DB2 Summit in Dallas, March 17-19

    IBM Layoffs Not As Dramatic As Rumored Orchestrating Your API-Enabled Assets On IBM i

    Leave a Reply Cancel reply

Volume 15, Number 03 -- February 10, 2015
THIS ISSUE SPONSORED BY:

ProData Computer Services
COMMON
WorksRight Software

Table of Contents

  • Create Excel Spreadsheets From DB2 Data With PHPExcel
  • Row Value Expressions Simplify Complex Row Selection
  • Git To It

Content archive

  • The Four Hundred
  • Four Hundred Stuff
  • Four Hundred Guru

Recent Posts

  • Liam Allan Shares What’s Coming Next With Code For IBM i
  • From Stable To Scalable: Visual LANSA 16 Powers IBM i Growth – Launching July 8
  • VS Code Will Be The Heart Of The Modern IBM i Platform
  • The AS/400: A 37-Year-Old Dog That Loves To Learn New Tricks
  • IBM i PTF Guide, Volume 27, Number 25
  • Meet The Next Gen Of IBMers Helping To Build IBM i
  • Looks Like IBM Is Building A Linux-Like PASE For IBM i After All
  • Will Independent IBM i Clouds Survive PowerVS?
  • Now, IBM Is Jacking Up Hardware Maintenance Prices
  • IBM i PTF Guide, Volume 27, Number 24

Subscribe

To get news from IT Jungle sent to your inbox every week, subscribe to our newsletter.

Pages

  • About Us
  • Contact
  • Contributors
  • Four Hundred Monitor
  • IBM i PTF Guide
  • Media Kit
  • Subscribe

Search

Copyright © 2025 IT Jungle