简体   繁体   English

cakephp将数据导出到excel或csv文件

[英]cakephp export data into excel or Csv file

i am working on a Cakephp 2.x .. i am using this solution for exporting data into excel sheet .. the problem is i dont know how can i add the column names or headings and then put data under the columns .. 我正在CakePHP 2.x上工作..我正在使用解决方案将数据导出到Excel工作表..问题是我不知道如何添加列名或标题,然后将数据放在列下..

for example here is what i am doing at the moment 例如,这是我目前正在做的事情

$this->CSV->addRow(array_keys($line));
 foreach ($Contacts as $contact)
 {
      $line = $contact['Contact'];

       $this->CSV->addRow($line);
 }

$filename='orders';
 echo  $this->CSV->render($filename); 

what i want to make my excel sheet is like this as when i do in my view pages .. 我要制作我的Excel工作表时就像在查看页面中那样。

      <table>

<tr>

    <th>Title</th>
    <th>Body</th>
    <th>Actions</th>
</tr>
<?php foreach($contacts as $contacts){?>
    <tr>

        <td> hello</td>
        <td> hello</td>
        <td> hello</td>
     </tr>
 }
    ?>

My recommendation is to use PHPExcel. 我的建议是使用PHPExcel。

Here is what I have done: 这是我所做的:

I downloaded the PHPExcel files into Vendor folder. 我将PHPExcel文件下载到Vendor文件夹中。

My structure is now: 我的结构现在是:

app 
  |---Vendor
        |----- PHPExcel
                   |----PHPExcel
                   |----PHPExcel.php

I needed to make my own forked changes to the PHPExcel for my own reasons. 由于我自己的原因,我需要对PHPExcel进行自己的分叉更改。 Hence I downloaded a copy instead of using the latest from repository with a package management solution like git submodules or composer. 因此,我下载了一个副本,而不是使用仓库中的最新版本以及git子模块或composer之类的软件包管理解决方案。 Feel free to use those. 随意使用它们。

Then I wrote my own Lib code in my cakephp app. 然后,我在cakephp应用程序中编写了自己的库代码。

app 
  |---Lib
        |----- Print
                   |----Excel
                          |----SomeExcel.php
                          |----AnotherExcel.php

I wrote two classes SomeExcel and AnotherExcel because I needed to generate two different excel files. 我写了两个类SomeExcelAnotherExcel因为我需要生成两个不同的excel文件。

Inside SomeExcel I wrote something like this: SomeExcel我写了这样的东西:

require_once(APP . DS . 'Vendor' . DS . 'PHPExcel' . DS . 'PHPExcel.php');

class SomeExcel {
    private $yourOwnPrivateProperty;
    private $objPHPExcel;

    public function __construct($data) {
        $this->objPHPExcel    = new PHPExcel();
        $this->objPHPExcel->writeDebugLog = true;

        $this->_createFilename();

    }

    public function create() {
        // you have to study PHPExcel yourself and write this
        $this->_setFileProperties();
        // you have to study PHPExcel and write whatever you want
        $this->_createSheets();
        $result = $this->_save();

        if ($result) {
            return $this->_getAttachmentFormat();
        } else {
            return $result;
        }
    }

    protected function _save() {
        $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel2007');
        /* I will create the folder inside the webroot outputfiles folder 
         * in case it does not exist.
         * I am not going to provide it here as it is not relevant to the question.
         * You need to write your own.
         */
        $this->_createFolder(); 
        try {
            $objWriter->save($this->outputPath . $this->filename);
        } catch (Exception $e) {
            return false;
        }
        return true;
    }

    protected function _getAttachmentFormat() {
        return array(
            $this->filename => array(
                'file' => $this->outputPath . $this->filename,
                'mimetype' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'contentId' => 'excelfile-for-something'
            )
        );
    }

The AnotherExcel class is similar. AnotherExcel类与此类似。

Usually it is a controller action that triggers the generation of an Excel file. 通常,这是触发Excel文件生成的控制器操作。 However, to obey the FatModel-ThinController principle, I have a Model method to do that. 但是,为了遵守FatModel-ThinController原理,我有一个Model方法来做到这一点。

So I have a controller action that is like this: 所以我有一个控制器动作是这样的:

/**
 * print_to_excel method (testing only)
 *
 * @return void
 */
public function print_to_excel($id = null) {
    set_time_limit(120);
    $result = $this->SomeModel->printExcel($id);

    if (is_array($result)){
        $filename = key($result);
        $this->redirect('/outputfiles/Excel/' . $id . '/' . $filename);
    }
}

Inside my SomeModel, I have the following: 在我的SomeModel中,我具有以下内容:

/**
 *
 * print excel file for said Quotation
 *
 * @param $id Quotation id
 * @throws NotExistException
 * @return boolean Return true if successful
 */
public function printExcel($id = null) {
    if (!$this->exists($id)) {
        throw new NotFoundException(__('Invalid whatever'));
    }


    $data = $this->find('first', array(
        'conditions' => array('SomeModel.id' => $id),
    ));

    // do whatever you need to get the data you want printed in the Excel

    App::uses('SomeExcel', 'Lib/Print/Excel');

    $someExcel = new SomeExcel($data);

    return $someExcel->create();
}

This is my way of using Excel and CakePHP 这是我使用Excel和CakePHP的方式

It is one way, but not the only way. 这是一种方法,但不是唯一的方法。

I am also proud to tell you that this is the exact code I use for an enterprise app I wrote for a major telco company to do their own internal digital paperwork. 我也很自豪地告诉您,这是我为一家大型电信公司编写的企业应用程序使用的确切代码,以完成自己的内部数字文书工作。

It is used by at least 10 people in that company. 该公司至少有10个人使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM