• 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:

    • Share on Reddit (Opens in new window) Reddit
    • Share on Facebook (Opens in new window) Facebook
    • Share on LinkedIn (Opens in new window) LinkedIn
    • Share on X (Opens in new window) X
    • Email a link to a friend (Opens in new window) Email

    Tags:

    Sponsored by
    JAMS Software

    One Scheduler. IBM i, Windows, Linux, and More.

    IBM i teams trust JAMS to schedule and orchestrate jobs across every platform in their environment. Centralized visibility, cross-platform dependency management, and alerts that reach the right person before the business feels it.

    Fewer than 5% of IBM i shops run IBM i only. The rest are managing cross-platform dependencies — often without a clear picture of how they connect. JAMS draws that map, enforces those dependencies automatically, and gives your team a single place to monitor, manage, and recover when something goes wrong.

    If you are running hundreds of CL scripts and custom RPG processes, bring them as-is. JAMS runs them exactly as they do today — except now they are visible, monitored, and part of an orchestrated workflow instead of scattered across folders only one person knows about.

    No consumption-based pricing. No surprise bills when your workload spikes. You pay based on how many machines JAMS talks to — that’s it.

    Learn More → https://jamsscheduler.com/lp/ibm-i

    Share this:

    • Share on Reddit (Opens in new window) Reddit
    • Share on Facebook (Opens in new window) Facebook
    • Share on LinkedIn (Opens in new window) LinkedIn
    • Share on X (Opens in new window) X
    • Email a link to a friend (Opens in new window) 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 Row Value Expressions Simplify Complex Row Selection

    Leave a ReplyCancel 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

  • IBM i PTF Guide, Volume 28, Number 28: A Crazy Number of Security Vulnerability Patches
  • Inside The Encryption Key Management Changes In IBM i 7.6
  • FalconStor Moved To The Blue Lagoon, And Is Poised For Growth Because Of It
  • Guru: Claude’s SQL Tip
  • Astera Makes Extracting Legacy Report Data an AI Specialty
  • IBM i PTF Guide, Volume 28, Number 27
  • Welcoming The New IBM i Chief Architect And Other New Top Brass
  • A Deep Dive Into That Power S1112 Entry Power11 Server
  • Guru: Beyond Three-Part Naming – Running SQL Across Remote IBM i Systems
  • How IBM Bolstered IBM i Resilience In The Summer Tech Refreshes

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