php excel动态添加列标题

时间:2018-05-03 12:08:16

标签: php excel codeigniter phpexcel

我想使用phpexcel和CodeIgniter在我现有的Excel工作表中追加带有标题的列。

我尝试了以下代码,但它没有在文件中写任何内容。

public function write() {
    $this->load->model('excel_import_model');
    $this->load->library('excel');


    $inputFileName = FCPATH . 'uploads/excel/sample.csv';

    //  Read your Excel workbook
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
    $objPHPExcel->getActiveSheet()->setCellValue('E1', 'test');
}

说明:我现在有数据到D列,我想使用E列,将标题添加为E列的project_link。 参考下面给出的图像: enter image description here

1 个答案:

答案 0 :(得分:0)

public function write() { 
    $this->load->model('excel_import_model');
    $this->load->library('excel');


    $inputFileName = FCPATH . 'uploads/excel/sample.csv';

    //  Read your Excel workbook
    try {
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
    } catch (Exception $e) {
        die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
    }
    $objPHPExcel->getActiveSheet()->setCellValue('E1','test');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
    $objWriter->save($inputFileName);
}

您需要使用保存功能编写文件,请参阅代码的最后两行,希望它能正常工作