We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 6094
    • 60 Posts
    Need a little help figuring this out. I know zero about PHP so I’m kind of stumbling through this at the moment. I’m trying to get data from my custom table exported to an Excel spreadsheet. I don’t really care if it’s Excel or CSV so if one is easier than the other please feel free to share.

    I start working with Bob’s Custom Tables tutorial (http://bobsguides.com/custom-db-tables.html), good stuff. I managed to get it working and then I created my own table for a project I’m working on made my connection and managed to get data to display. Felt pretty good about that. Then I changed the formatting from the tutorial and had everything displaying in a nice neat table, so everything is still good to this point. Next, I wanted to export the data to an Excel spreadsheet and this is where my issues reside.

    Here is the code I have in the snippet that is called on the page.
    <?php
    $path = MODX_CORE_PATH . 'components/brochure/';
    $result = $modx->addPackage('brochure',$path . 'model/','stone_');
    $filename ="excelreport.xls";
    $brochures = $modx->getCollection('Brochure'); 
    
    
    foreach($brochures as $brochure) {
    
        $output .= $brochure->get('name')."\t";
        $output .= $brochure->get('street')."\t";
        $output .= $brochure->get('city')."\t";
        $output .= $brochure->get('state')."\t";
        $output .= $brochure->get('zip')."\t";
        $output .= $brochure->get('email')."\t \n";
    }
    
    header('Content-type: application/ms-excel');
    header('Content-Disposition: attachment; filename='.$filename);
    return $output;


    So, for all practical purposes this will output and Excel file but it doesn’t really format it. all the data is lined up in order in the first cell with no separation. Does anyone know what I’m doing wrong or how this is actually achieved?

    As always, thanks in advance.
      • 3749
      • 24,544 Posts
      I think you’ve have to go CSV, unless you want implement a tool that writes Excel-format files.

      Change the "\t" to ’,’ and I think you’ll be set. Make the file extention *.csv and Excel should pull it right in.
        Did I help you? Buy me a beer
        Get my Book: MODX:The Official Guide
        MODX info for everyone: http://bobsguides.com/modx.html
        My MODX Extras
        Bob's Guides is now hosted at A2 MODX Hosting
        • 6094
        • 60 Posts
        Thanks so much for your response.

        I think I’m close, but that’s not really getting done. When I open the file it’s not returning the second record to the next row. Do you happen to know what code to use on the the end of this line?
        $output .= $brochure->get('email')


        Other than that it seems to work fine.
          • 6094
          • 60 Posts
          Ok, I have it figured out. Thanks so much for your help. I’m not sure if this is the most efficient way, but I will include the code in case someone else needs it in the future.
          <?php
          $path = MODX_CORE_PATH . 'components/brochure/';
          $last = "\n";
          $result = $modx->addPackage('brochure',$path . 'model/','stone_');
          $filename ="excelreport.csv";
          $brochures = $modx->getCollection('Brochure'); 
          
          
          
          foreach($brochures as $brochure) {
          
              $output .= $brochure->get('name').',';
              $output .= $brochure->get('street').',';
              $output .= $brochure->get('city').',';
              $output .= $brochure->get('state').',';
              $output .= $brochure->get('zip').',';
              $output .= $brochure->get('email').',';
              $output .= $last;
          }
          
          header('Content-type: application/ms-excel');
          header('Content-Disposition: attachment; filename='.$filename);
          return $output;

            • 3749
            • 24,544 Posts
            Looks good. Just for fun, you might try this inside the loop instead of all the assignments (assuming that you want all brochure fields):

            $outout .= implode(',', $brochure->toArray()) . "\n";


              Did I help you? Buy me a beer
              Get my Book: MODX:The Official Guide
              MODX info for everyone: http://bobsguides.com/modx.html
              My MODX Extras
              Bob's Guides is now hosted at A2 MODX Hosting
              • 6094
              • 60 Posts
              That works great and with less code.
              Thanks for your help.
                • 24013
                • 7 Posts
                This is exactly what I’m needing, but I’m running into an issue.

                I am using xdbedit to create a CMP for managing custom table data. I have everything working just fine except the export functionality. What I’d like is to add an export button to the actions section. When clicking on that button the export should be forced to download.

                Here is my export.php processor:

                <?php 
                
                $config=$modx->xdbedit->customconfigs;
                $prefix = $config['prefix'];
                $packageName = $config['packageName'];
                $tablename = $config['tablename'];
                
                $packagepath = $modx->getOption('core_path') . 'components/'.$packageName.'/';
                $modelpath = $packagepath.'model/';
                
                $modx->addPackage($packageName,$modelpath,$prefix);
                $classname = $modx->xdbedit->getClassName($tablename);
                
                if ($this->modx->lexicon)
                {
                    $this->modx->lexicon->load($packageName.':default');
                }
                
                /* setup default properties */
                $isLimit = !empty($scriptProperties['limit']);
                $isCombo = !empty($scriptProperties['combo']);
                $start = $modx->getOption('start',$scriptProperties,0);
                $limit = $modx->getOption('limit',$scriptProperties,20);
                $sort = $modx->getOption('sort',$scriptProperties,'id_req');
                $dir = $modx->getOption('dir',$scriptProperties,'ASC');
                $year = $modx->getOption('year',$scriptProperties,'all');
                $month = $modx->getOption('month',$scriptProperties,'all');
                $showtrash = $modx->getOption('showtrash',$scriptProperties,'');
                
                $c = $modx->newQuery($classname);
                
                $count = $modx->getCount($classname,$c);
                
                $c->select('
                    `'.$classname.'`.*
                ');
                
                $collection = $modx->getCollection($classname, $c);
                
                
                foreach($collection as $item) {
                	$output .= implode(',', str_replace("\r\n","",$item->toArray())) . PHP_EOL;
                }
                header('Content-type: application/csv');
                header('Content-Disposition: attachment; filename=excelreport.csv');
                header("Content-Type: application/force-download");
                header("Cache-Control: post-check=0, pre-check=0", false);
                return $output;
                
                


                In my button group I have added (this successfully adds the button):

                				},{
                                    text: _(Xdbedit.customconfigs.task + '.export') || _('xdbedit.export')
                                    ,handler: this.export_items
                                    ,enableToggle: false
                                    ,scope: this
                


                and for my export_items function is have:

                	,export_items: function() {
                        MODx.Ajax.request({
                            url: this.config.url
                            ,params: {
                                action: 'mgr/'+Xdbedit.customconfigs.task+'/export'
                				,task: 'export'
                				,configs: this.config.configs
                            }
                        });
                    }
                


                The error I’m getting is "missing ) in parenthetical".

                In Firebug, the console’s POST response shows all of the data correctly.

                However, the net response for connector.php doesn’t show anything.

                Can you help?? The client is coming in tomorrow morning for a MODx training and this is the last item to build out. Thanks!!
                  44+ MODXed sites and counting...