PHPexcel到数组。帮助格式化数组并清除NULL值数组

时间:2016-04-14 16:16:00

标签: php arrays excel xls

我的电子表格将始终包含B,C,D,E,F,G行3 =地址,姓名,电话,部门等。来自下方单元格的数据(一些空的一些人口)1234 x street, 1234 y street,555-5555,HR等。所以如果我的阵列看起来像这样:

[1] =>array(
    ['address1'] =>'1234 x street'
    ['name1'] =>'1234 y street'
    ['phone1'] =>'555-5555'
     ...etc
    ['department1'] =>'HR'

[2] =>array(
    ['address2'] =>'1234 x street'
    ['name2'] =>'1234 y street'
    ['phone2'] =>'555-5555'
     ...etc
    ['department2'] =>'HR'

我目前的代码是:

    <SNIP>
    $objReader->setReadDataOnly(true); 
    $objPHPExcel = $objReader->load($inputFileName);
    $objWorksheet = $objPHPExcel->getActiveSheet();

        if($header){
            $highestRow = $objWorksheet->getHighestRow();
            $highestColumn = $objWorksheet->getHighestColumn();
            $headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
            $headingsArray = $headingsArray[1];
            $r = -1;
            $namedDataArray = array();
            for ($row = 2; $row <= $highestRow; ++$row) {
                $dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
                if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
                    ++$r;
                    foreach($headingsArray as $columnKey => $columnHeading) {
                        $namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
                }
            }
        }
    }
    else{
        $namedDataArray = $objWorksheet->toArray(null,true,true,true);

}

研究表明我可以使用以下方法之一,但我需要帮助将它们放在一起:

    $column = 'IV';
    $columnIndex = PHPExcel_Cell::columnIndexFromString($column);


    $adjustment = -2;
    $currentColumn = 'BZ';

    $columnIndex = PHPExcel_Cell::columnIndexFromString($currentColumn);
    $adjustedColumnIndex = $columnIndex + $adjustment;
    $adjustedColumn = PHPExcel_Cell::stringFromColumnIndex($adjustedColumnIndex - 1);

1 个答案:

答案 0 :(得分:0)

我最终没有使用任何本地类来进行排序,只需按照以下方式自行编写,降低开销:

            <?php
            //require 'FirePHPCore/fb.php';  This section was just to use FirePHP so I could see the JSON output without using html.
            //ob_start('ob_gzhandler');
            //FB::info('Hello, FirePHP');
            //FB::log('Log message');
            //FB::info('Info message');
            //FB::warn('Warn message');
            //FB::error('Error message');

            require_once dirname(__FILE__) . '/classes/PHPExcel.php';
            //  Include PHPExcel_IOFactory
            include 'classes/PHPExcel/IOFactory.php';
            $inputFileName = './uploads/fw.xls';

            $inputFileType = PHPExcel_IOFactory::identify($inputFileName);/**  Identify the type of $inputFileName  **/
            $objReader = PHPExcel_IOFactory::createReader($inputFileType);/**  Create a new Reader of the type that has been identified  **/
            $objReader->setReadDataOnly(true); /** Set read type to read cell data only **/
            $objPHPExcel = $objReader->load($inputFileName);/**  Load $inputFileName to a PHPExcel Object  **/
            $objWorksheet = $objPHPExcel->getActiveSheet();//Get worksheet and built array with first row as header


            // stuff all tabs into their own array
            $sheetNames = $objPHPExcel->getSheetNames();
            foreach ($sheetNames as $sheet) {
               $sheet2 = preg_replace("/\s+/","_",$sheet);
               //print "$sheet: $sheet2<br>\n";
              ${$sheet2} = $objPHPExcel->getSheetByName($sheet);
            }
            // print_r($Network_Security);
            //exit;


            // parse each tab, tack onto end of $prejson array
            $prejson = [];

            // parse network security
            //use class to find data range
            $highestRow = $Network_Security->getHighestRow();
            $range = $Network_Security->calculateWorksheetDimension();
            // manually narrow range columns
            $range = preg_replace("/A/","B",$range);
            $range = preg_replace("/L/","K",$range);
            //create array of data rows
            $rows = $Network_Security->rangeToArray($range);
            $active = 0;
            //loop through each row
            foreach ($rows as $row) {
              if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
              if (preg_match("/^Line/",$row[0]) && $active == 0) { $active = 1; } //show header
              if ($row[0] == "") { $active = 0; continue; }
              if ($active == "1") {
                //key array
                array_unshift($row,"netsec");
                // stuff to prejson
                array_push($prejson,$row);
              }
            }
            // end netsec

            // parse network translation
            $highestRow = $Network_Translation->getHighestRow();
            $range = $Network_Translation->calculateWorksheetDimension();
            $range = preg_replace("/A/","B",$range);
            $range = preg_replace("/J/","G",$range);
            $rows = $Network_Translation->rangeToArray($range);
            $active = 0;
            foreach ($rows as $row) {
              if (preg_match("/^Source/",$row[0]) && $active == 0) { $active = 1; } //show header
              if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
              if ($row[0] == "") { $active = 0; continue; }
              if ($active == "1") {
                //key array
                array_unshift($row,"nettrans");
                // stuff to prejson
                array_push($prejson,$row);
              }
            }
            // end nettrans

            // parse routing
            $highestRow = $Routing->getHighestRow();
            $range = $Routing->calculateWorksheetDimension();
            $range = preg_replace("/A/","B",$range);
            $range = preg_replace("/H/","G",$range);
            $rows = $Routing->rangeToArray($range);
            $active = 0;
            foreach ($rows as $row) {
              if (preg_match("/Do not edit the data/",$row[0])) { $active = 2; continue; }
              //if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; continue; } //hide header
              if (preg_match("/^Add/",$row[0]) && $active == 0) { $active = 1; } //show header
              if ($row[0] == "") { $active = 0; continue; }
              if ($active == "1") {
                // key array
                array_unshift($row,"rtg");
                // stuff to prejson
                array_push($prejson,$row);
              }
            }
            // end routing

            //print "<pre>";
            //var_dump($prejson);
            $json = json_encode($prejson);
            //$json_string = prettyPrint($json);
            $json_string = json_encode($json,JSON_PRETTY_PRINT);  //remove ,JSON_PRETTY_PRINT
            print $json;
            //print "</pre>";

            function prettyPrint( $json )
            {
                $result = '';
                $level = 0;
                $in_quotes = false;
                $in_escape = false;
                $ends_line_level = NULL;
                $json_length = strlen( $json );

                for( $i = 0; $i < $json_length; $i++ ) {
                    $char = $json[$i];
                    $new_line_level = NULL;
                    $post = "";
                    if( $ends_line_level !== NULL ) {
                        $new_line_level = $ends_line_level;
                        $ends_line_level = NULL;
                    }
                    if ( $in_escape ) {
                        $in_escape = false;
                    } else if( $char === '"' ) {
                        $in_quotes = !$in_quotes;
                    } else if( ! $in_quotes ) {
                        switch( $char ) {
                            case '}': case ']':
                                $level--;
                                $ends_line_level = NULL;
                                $new_line_level = $level;
                                break;

                            case '{': case '[':
                                $level++;
                            case ',':
                                $ends_line_level = $level;
                                break;

                            case ':':
                                $post = " ";
                                break;

                            case " ": case "\t": case "\n": case "\r":
                                $char = "";
                                $ends_line_level = $new_line_level;
                                $new_line_level = NULL;
                                break;
                        }
                    } else if ( $char === '\\' ) {
                        $in_escape = true;
                    }
                    if( $new_line_level !== NULL ) {
                        $result .= "\n".str_repeat( "\t", $new_line_level );
                    }
                    $result .= $char.$post;
                }

                return $result;
            }
            ?>

现在我只需要获取钩子,这样当dropzone.js完成时它将自动填充.js表单。