php - CodeIgniter:将数据从数据库导出到 excel 并下载

标签 php mysql excel codeigniter export-to-excel

我正在从事一个项目,该项目需要根据多种条件从 MYSQL 数据库中导出数据。我指的是 this :

这是我的源代码:

public function exportExcelData($records)
{
  $heading = false;
        if (!empty($records))
            foreach ($records as $row) {
                if (!$heading) {
                    // display field/column names as a first row
                    echo implode("\t", array_keys($row)) . "\n";
                    $heading = true;
                }
                echo implode("\t", ($row)) . "\n";
            }
 }

public function fetchDataFromTable()
{
     $query =$this->db->get('one_piece_characters'); // fetch Data from table
     $allData = $query->result_array();  // this will return all data into array
     $dataToExports = [];
     foreach ($allData as $data) {
        $arrangeData['Charater Name'] = $data['name'];
        $arrangeData['Charater Profile'] = $data['profile'];
        $arrangeData['Charater Desc'] = $data['description'];
        $dataToExports[] = $arrangeData;
  }
  // set header
  $filename = "dataToExport.xls";
                header("Content-Type: application/vnd.ms-excel");
                header("Content-Disposition: attachment; filename=\"$filename\"");
  $this->exportExcelData($dataToExports);
 }

如果我在没有任何 where 子句的情况下使用它,它会给出整个表。

如果我只使用单个 where 子句,效果很好。

Bur,如果我使用多个 where 条件。它给了我一张空白的 Excel 工作表。

有没有人知道如何让它在多个 where 条件下工作?

最佳答案

尝试在您的模型文件中使用此代码:

function createcsv(){
        $this->load->dbutil();
        $this->load->helper('file');
        $this->load->helper('download');
        $delimiter = ",";
        $newline = "\r\n";
        $filename = "filename.csv";
        $query = "SELECT * FROM YourTable"; //USE HERE YOUR QUERY
        $result = $this->db->query($query);
        $data = $this->dbutil->csv_from_result($result, $delimiter, $newline);
        force_download($filename, $data);

    }

关于php - CodeIgniter:将数据从数据库导出到 excel 并下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39806663/

相关文章:

excel - 尝试重命名工作表时星号不起作用

php - 即使页面存在,mod_rewrite 中的最后一条规则也会返回 404

PHP:创建类似 PHP 的浏览器

php - 我怎样才能防止这个脚本被随意访问?

MySQL INFORMATION_SCHEMA 表未填充

php - 在 MySQL 中创建表时出错

php - 如何在 php 中获取 session ID 或用户名?

MYSQL 查询连接表

excel - 如何编写具有多个条件样式的 sumproduct 以避免在 Excel 中添加额外的列

vba - 从 Excel 中获取数据并插入到预先存在的 Word 表中?