phpcsvphpexcelyii2-advanced-appphpexcelreader

Import CSV file with tab delimited using PHPExcel lib


I'm trying to import CSV file using PHPExcel lib. My CSV file has \t or tab as delimiter.

So when I'm trying to printout the result in my screen, every comma seen as new cell, just like this enter image description here

But actually I need to export data in one line for each row and separated by quotation-sign (") for each tab delimiter, just like this one enter image description here

This is my code in Controller for reading and write the data:

$worksheet = $objPHPExcelDetail->getActiveSheet();
        foreach ($worksheet->getRowIterator() as $row) {
                echo '<pre>';
                echo 'Row number: ' . $row->getRowIndex() . "\r\n";

                $cellIterator = $row->getCellIterator();
                $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set     

                foreach ($cellIterator as $cell) {
                    if (!is_null($cell)) {
                        echo 'Cell: ' . $cell->getCoordinate() . ' - ' . $cell->getValue() . "\r\n";
                    }
                }
        }

How can I read CSV file with \t separator, and set into one line for each row?


Solution

  • It's the code for loading the file that you need to think about.

    Look at the methods available to the CSV Reader in the PHPExcel Documentation.... you'll find that there is a setDelimiter() method that allows you to say to use a tab rather than a ,.

    $objReader = PHPExcel_IOFactory::createReader('CSV')
        ->setDelimiter("\t");
    $objPHPExcel = $objReader->load($myFileName);