• 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
    Raz-Lee Security

    Start your Road to Zero Trust!

    Firewall Network security, controlling Exit Points, Open DB’s and SSH. Rule Wizards and graphical BI.

    Request Demo

    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

  • Public Preview For Watson Code Assistant for i Available Soon
  • COMMON Youth Movement Continues at POWERUp 2025
  • IBM Preserves Memory Investments Across Power10 And Power11
  • Eradani Uses AI For New EDI And API Service
  • Picking Apart IBM’s $150 Billion In US Manufacturing And R&D
  • FAX/400 And CICS For i Are Dead. What Will IBM Kill Next?
  • Fresche Overhauls X-Analysis With Web UI, AI Smarts
  • Is It Time To Add The Rust Programming Language To IBM i?
  • Is IBM Going To Raise Prices On Power10 Expert Care?
  • IBM i PTF Guide, Volume 27, Number 20

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