Introduction to php processing Excel steps

Introduction to the steps of processing Excel in php Problems
encountered
At work, there is often a need to export database tables to Excel or import Excel into database tables. This requirement has been fulfilled long ago. In order to facilitate import and export, Brothers www.lampbrother.net divided it into two methods as records.

The code implements
the reference of the phpexcel class library.
Phpexcel has powerful Excel processing capabilities and has been downloaded millions of times on packagist, but to be honest, the processing speed of excel is still very slow, and it should be used with caution when the amount of data is large. After downloading on packagist or directly using composer require phpoffice/phpexcel, you can use phpexcel.

Export to Excel
In most cases, exporting excel is actually converting a two-digit array into a table.

    use namespace PHPExcel;
    /**
     * @param $name string The name of the Excel to save
     * @param $ret_data Convert to a two-dimensional array of tables
     * @throws PHPExcel_Exception
     * @throws PHPExcel_Reader_Exception
     */
    function exportExcel($name, $ret_data) {
        $objPHPExcel = new PHPExcel();
        //设置表格
        $objPHPExcel->getProperties()->setCreator($name)
                ->setLastModifiedBy($name)
                ->setTitle("Office 2007 XLSX Test Document")
                ->setSubject("Office 2007 XLSX Test Document")
                ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                ->setKeywords("office 2007 openxml php")
                ->setCategory("Test result file");
        //填充数据
        foreach ($ret_data as $key => $row) {
            $num = $key + 1;
            //$row = array_values($row);
            $i=0;
            foreach ($row as $key2 => $value2) {
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue( Cell::stringFromColumnIndex($i). ($num), $value2);
                $i++;
            }
        }
        //设置表格并输出
        $objPHPExcel->getActiveSheet()->setTitle($name);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename={$name}.xls");
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: cache, must-revalidate');
        header('Pragma: public');// HTTP/1.0
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    } Similarly to importing
Excel

, importing Excel is actually converting Excel data into two dimensional array, which requires Excel to conform to the format.
function getRows($inputFileName)
    {
        if (!file_exists($inputFileName)) {
            throw new Exception("File not existed");
        }
        $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
        $objReader = PHPExcel_IOFactory::createReader($ inputFileType);
        $objPHPExcel = $objReader->load($inputFileName);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
        $row = 1;
        $curr = array();
        while ($row <= $highestRow) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $value = str_replace(array("\n", "\n\r", "\r"), "", $objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
                $curr[$row][] = $value;
            }
            $row++;
        }
        array_shift($curr);//The first line is generally the field name (the title of the column in Excel), which should be removed when importing }
        return $curr;


Others The format saved when
exporting is xlsx. If you want to change to other formats, you need to pass in different parameters.
When importing, if there are multiple sheets, you need to close the sheet page to be imported (to ensure that the current sheet is the active Sheet) when you opened it last time, or select the sheet in the program according to the sheet name.

Guess you like

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