如何从一个excel复制列值并写入另一个excel?

时间:2017-06-08 07:05:53

标签: php mysql excel phpexcel

我有一个Excel说“A”,列名为Name,Email和Address。我需要将它复制到另一个excel,它有订单电子邮件,名称和地址。我怎么能用PHP Excel Class做到这一点?请帮忙

1 个答案:

答案 0 :(得分:0)

 function  stack(){
    Include 'PHPExcel_IOFactory';
    include 'PHPExcel/IOFactory.php';
    $inputFileName = '/example1.xls';

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

    //  Get worksheet dimensions
    $sheet = $objPHPExcelOri->getSheet(0); 
    $highestRow = $sheet->getHighestRow(); 
    $highestColumn = $sheet->getHighestColumn();

    //  Loop through each row of the worksheet in turn
    for ($row = 1; $row <= $highestRow; $row++){ 
        //  Read a row of data into an array
        $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
                                        NULL,
                                        TRUE,
                                        FALSE);
        //  Save data in Array
        $dataOri[$row]=$rowData[0];
    }


    //NEW EXCEL
    self::$objPHPExcel->createSheet();
    self::$objPHPExcel->setActiveSheetIndex();

    $rowNew = 1;
    foreach ($dataOri as $key => $data) {
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'A' . $rowNew , $data[1] );
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'B' . $rowNew , $data[0] );
          self::$objPHPExcel->getActiveSheet()->setCellValue(  'C' . $rowNew++ , $data[2] );
    }

    //Download EXCEL
    $filename = 'ExcelNew';
    $format = 'Excel2007';
    $this->saveExcelDownload($format, $filename);

}