Several examples of official reading of PHPExcel

1. Read the file using PHPExcel_IOFactory  
    $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);          
2. Use a specific read class to read the file  
    $objReader = new PHPExcel_Reader_Excel5();                    
    objPHPExcel = $objReader->load($inputFileName);  
3. Create a specific read class using PHPExcel_IOFactory  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);    
    $objPHPExcel = $objReader->load($inputFileName);  
    Read types are:  
        $inputFileType = 'Excel5';  
        $inputFileType = 'Excel2007';  
        $inputFileType = 'Excel2003XML';  
        $inputFileType = 'OOCalc';  
        $inputFileType = 'SYLK';  
        $inputFileType = 'Gnumeric';  
        $inputFileType = 'CSV';  
  
  
4. Use PHPExcel_IOFactory to identify which read class the file should use  
    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objPHPExcel = $objReader->load($inputFileName);  
5. Read only data, ignore various formats, etc. (For Excel read, it is greatly optimized)  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setReadDataOnly(true);  
    $objPHPExcel = $objReader->load($inputFileName);  
6. Load all worksheets in Excel  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setLoadAllSheets(); // load all sheets  
    $objPHPExcel = $objReader->load($inputFileName);  
    $objPHPExcel->getSheetCount(); // Get the number of worksheets  
    $objPHPExcel->getSheetNames(); // Get the name array of all sheets  
7. Load a single named worksheet  
    $sheetname = 'Data Sheet #2'; // single sheet, pass in string  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setLoadSheetsOnly($sheetname); // Load a single sheet, pass in the sheet name (eg: 'Data Sheet #2')  
    $objPHPExcel = $objReader->load($inputFileName);  
8. Load Multiple Named Worksheets  
    $sheetnames = array('Data Sheet #1', 'Data Sheet #2'); // Multiple sheets, pass in an array  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setLoadSheetsOnly($sheetnames); // Load multiple sheets, pass in an array of sheet names  
    $objPHPExcel = $objReader->load($inputFileName);  
9. Customize a read filter  
    class MyReadFilter implements PHPExcel_Reader_IReadFilter  
    {  
        public function readCell($column, $row, $worksheetName = '') {  
  
  
            // Read only the cells in rows 1-7 & columns A-E  
            if ($row >= 1 && $row <= 7) {  
                if (in_array($column,range('A','E'))) {  
                    return true;  
                }  
            }  
            return false;  
        }  
    }  
    $filterSubset = new MyReadFilter();  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setReadFilter($filterSubset); // Set the instantiated filter object  
    $objPHPExcel = $objReader->load($inputFileName);  
10. It is also a custom read filter, but the range of rows and columns to be read can be configured  
    class MyReadFilter implements PHPExcel_Reader_IReadFilter  
    {  
        private $_startRow = 0; // start row  
        private $_endRow = 0; // end row  
        private $_columns = array(); // column span  
        public function __construct($startRow, $endRow, $columns) {  
            $this->_startRow = $startRow;  
            $this->_endRow       = $endRow;  
            $this->_columns      = $columns;  
        }  
        public function readCell($column, $row, $worksheetName = '') {  
            if ($row >= $this->_startRow && $row <= $this->_endRow) {  
                if (in_array($column,$this->_columns)) {  
                    return true;  
                }  
            }  
            return false;  
        }  
    }  
    $filterSubset = new MyReadFilter(9,15,range('G','K'));  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setReadFilter($filterSubset); // Set the instantiated filter object  
    $objPHPExcel = $objReader->load($inputFileName);  
11. Read Excel in blocks, the principle is still: custom read filter  
    class chunkReadFilter implements PHPExcel_Reader_IReadFilter  
    {  
        private $_startRow = 0; // start row  
        private $_endRow = 0; // end row  
        public function __construct($startRow, $chunkSize) { // we need to pass: start row number & row span (to calculate end row number)  
            $this->_startRow = $startRow;  
            $this->_endRow       = $startRow + $chunkSize;  
        }  
        public function readCell($column, $row, $worksheetName = '') {  
            if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {  
                return true;  
            }  
            return false;  
        }  
    }  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $chunkSize = 20; // Define the number of lines read per chunk  
  
  
    // You can read the block multiple times in a loop instead of reading the entire Excel table into memory at once  
    for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) {  
        $chunkFilter = new chunkReadFilter($startRow, $chunkSize);  
        $objReader->setReadFilter($chunkFilter); // Set the instantiated filter object  
        $objPHPExcel = $objReader->load($inputFileName);  
        // Start reading each row of data and insert it into the database  
    }  
12. Read version 2 of Excel in chunks  
    class chunkReadFilter implements PHPExcel_Reader_IReadFilter  
    {  
        private $_startRow = 0; // start row  
        private $_endRow = 0; // end row  
  
  
        // Defines a method to read the specified range of lines  
        public function setRows($startRow, $chunkSize) {  
            $this->_startRow = $startRow;  
            $this->_endRow       = $startRow + $chunkSize;  
        }  
        public function readCell($column, $row, $worksheetName = '') {  
            if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {  
                return true;  
            }  
            return false;  
        }  
    }  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $chunkSize = 20; // Define the number of lines read per chunk  
  
  
    // Outside the loop, instantiate the filter class instead of each instantiation inside the loop (should be more optimized)  
    $chunkFilter = new chunkReadFilter();  
    $objReader->setReadFilter($chunkFilter);  
    for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) {  
  
  
        // Inside the loop, use the method of the instantiated object to adjust the range of lines read  
        $chunkFilter->setRows($startRow,$chunkSize);  
        $objPHPExcel = $objReader->load($inputFileName);  
    }  
13. Read multiple CSV files  
    $inputFileNames = array('./sampleData/example1.csv','./sampleData/example2.csv'); // array of CSV files  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
  
  
    /*  
        Explain what the following does:  
            1. First load the first CSV as the first worksheet | set the title of the worksheet  
            2. Re-enter multiple CSVs into the objPHPExcel object in turn, and append them to the Nth worksheet in turn | Set the title of the worksheet  
            3. Get all the titles of Excel at this time, get the worksheets in turn through the titles, and then operate on the worksheets!  
     */  
    $inputFileName = array_shift($inputFileNames); // first CSV file  
    $objPHPExcel = $objReader->load($inputFileName); // read the first CSV file  
    $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); // set the title  
    foreach($inputFileNames as $sheet => $inputFileName) {  
        $objReader->setSheetIndex($sheet+1); // switch sheet to next sheet  
        $objReader->loadIntoExisting($inputFileName,$objPHPExcel); // Load the next CSV file into the existing PHPExcel object  
        $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); // Set the title of the current worksheet  
    }  
  
  
    // loop through all worksheet names  
    $loadedSheetNames = $objPHPExcel->getSheetNames();  
    foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {  
        $objPHPExcel->setActiveSheetIndexByName($loadedSheetName); // Set the current worksheet as active by 'sheet name'  
        // Then read and write to the currently active worksheet  
    }  
14. Divide a large CSV file into multiple worksheets in 'chunks' (combining examples 12 & 13)  
    class chunkReadFilter implements PHPExcel_Reader_IReadFilter  
    {  
        private $_startRow = 0; // start row  
        private $_endRow = 0; // end row  
  
  
        // Defines a method to read the specified range of lines  
        public function setRows($startRow, $chunkSize) {  
            $this->_startRow = $startRow;  
            $this->_endRow       = $startRow + $chunkSize;  
        }  
        public function readCell($column, $row, $worksheetName = '') {  
            if (($row == 1) || ($row >= $this->_startRow && $row < $this->_endRow)) {  
                return true;  
            }  
            return false;  
        }  
    }  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $chunkSize = 100; // Define the number of lines read per chunk  
  
  
    // Outside the loop, instantiate the filter class instead of each instantiation inside the loop (should be more optimized)  
    $chunkFilter = new chunkReadFilter();  
    $objReader->setReadFilter($chunkFilter)  
              ->setContiguous(true); // Here's a method I haven't seen before (leave it first, forget what it's doing)  
  
  
    $objPHPExcel = new PHPExcel();  
    $sheet = 0; // first sheet index  
    for ($startRow = 2; $startRow <= 240; $startRow += $chunkSize) {  
        $chunkFilter->setRows($startRow,$chunkSize);  
        $objReader->setSheetIndex($sheet); // switch sheets  
        $objReader->loadIntoExisting($inputFileName,$objPHPExcel); // Load the read CSV block into the worksheet  
        $objPHPExcel->getActiveSheet()->setTitle('Country Data #'.(++$sheet)); // set sheet title  
    }  
  
  
    // loop through all worksheet names  
    $loadedSheetNames = $objPHPExcel->getSheetNames();  
    foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {  
        $objPHPExcel->setActiveSheetIndexByName($loadedSheetName); // Set the current worksheet as active by 'sheet name'  
        // Then read and write to the currently active worksheet  
    }  
  
  
15. Use 'Advanced Value Binder' to read a file with 'tab' separated values  
    PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() ); // set the cell  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $objReader->setDelimiter("\t"); // set the delimiter to '\t' (tab separated)  
    $objPHPExcel = $objReader->load($inputFileName);  
    $objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME)); // set the title  
    $loadedSheetNames = $objPHPExcel->getSheetNames(); // Get all sheet names  
  
  
    1) Format the output  
    foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {  
        $objPHPExcel->setActiveSheetIndexByName($loadedSheetName);  
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true); // Note the difference between the 4 parameters  
    }  
    2) Unformatted output  
    foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {  
        $objPHPExcel->setActiveSheetIndexByName($loadedSheetName);  
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,false,true); // Note the difference between the 4 parameters  
    }  
    3) Cell native value  
    foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {  
        $objPHPExcel->setActiveSheetIndexByName($loadedSheetName);  
        $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,false,false,true); // Note the difference between the 4 parameters  
    }  
16. Use 'try/catch' to control exceptions when Excel loads  
    try {  
        $objPHPExcel = PHPExcel_IOFactory::load($inputFileName);  
    } catch(PHPExcel_Reader_Exception $e) {  
        die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());  
    }  
17. Get a list of sheet names in Excel  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $worksheetNames = $objReader->listWorksheetNames($inputFileName); // list worksheet names  
    foreach($worksheetNames as $worksheetName) {  
        echo $worksheetName,'<br />';  
    }  
18. Do not load the entire file, or list of sheet names in Excel  
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);  
    $worksheetData = $objReader->listWorksheetInfo($inputFileName); // list worksheet  
    foreach ($worksheetData as $worksheet) {  
        echo '<li>', $worksheet['worksheetName'], '<br />';  
        echo 'Rows: ', $worksheet['totalRows'], ' Columns: ', $worksheet['totalColumns'], '<br />';  
        echo 'Cell Range: A1:', $worksheet['lastColumnLetter'], $worksheet['totalRows'];  
        echo '</li>';  
    }  
19. In the whole process, there is a method:  
    $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,false,false,true);  
    getActiveSheet() - Gets the currently active sheet  
    toArray() - puts the currently active worksheet, parsed all into an array  

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326611786&siteId=291194637