使用PHPExcel导出/导入CSV

使用PHPExcel导出/导入CSV,php,mysql,csv,phpexcel,Php,Mysql,Csv,Phpexcel,请您指导我或提供一些使用PHPExcel库执行CSV导出和导入的示例代码,好吗 Excel导出和导入很好,但我也需要CSV导出/导入。我有其他的CSV导出和导入方法,但是也可以通过PHPExcel完成吗?将CSV文件导入到PHPExcel对象中 $inputFileType = 'CSV'; $inputFileName = 'testFile.csv'; $objReader = PHPExcel_IOFactory::createReader($inputFileType); $objPHP

请您指导我或提供一些使用PHPExcel库执行CSV导出和导入的示例代码,好吗


Excel导出和导入很好,但我也需要CSV导出/导入。我有其他的CSV导出和导入方法,但是也可以通过PHPExcel完成吗?

将CSV文件导入到PHPExcel对象中

$inputFileType = 'CSV';
$inputFileName = 'testFile.csv';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save('testExportFile.csv');
从PHPExcel对象导出CSV文件的步骤

$inputFileType = 'CSV';
$inputFileName = 'testFile.csv';
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV');
$objWriter->save('testExportFile.csv');
编辑

如何读取行和单元格:

$worksheet = $objPHPExcel->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
    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";
        }
    }
}
如何写入PHPExcel对象: 您不会说您的数据来自何处:下面是如何从MySQL查询中执行此操作

$query = sprintf("SELECT firstname, lastname, age, date_of_birth, salary FROM employees WHERE firstname='%s' AND lastname='%s'",
                  mysql_real_escape_string($firstname),
                  mysql_real_escape_string($lastname));
$result = mysql_query($query);

$row = 1;
$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, 'First Name')
                              ->setCellValue('B'.$row, 'Last Name')
                              ->setCellValue('C'.$row, 'Age')
                              ->setCellValue('D'.$row, 'Date of birth')
                              ->setCellValue('E'.$row, 'Salary');
$row++;
while ($rec = mysql_fetch_assoc($result)) {
    $objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $rec['firstname'])
                                  ->setCellValue('B'.$row, $rec['lastname'])
                                  ->setCellValue('C'.$row, $rec['age'])
                                  ->setCellValue('D'.$row, PHPExcel_Shared_Date::stringToExcel($rec['date_of_birth']))
                                  ->setCellValue('E'.$row, $rec['salary']);
    $objPHPExcel->getActiveSheet()->getStyle('D'.$row)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15);
    $objPHPExcel->getActiveSheet()->getStyle('E'.$row)->getNumberFormat()->setFormatCode('£#,##0.00');
    $row++;
}

我一直在寻找同样的东西。Excel CSV并不总是使用引号分隔符,而是使用“”转义引号,因为该算法可能是在80年代或更早的时候提出的。在查看了PHP.NET评论部分中的几个.csv解析器之后,我看到了一些甚至使用回调或评估代码的解析器,它们要么无法正常工作,要么根本无法工作。因此,我为此编写了自己的例程,它们在最基本的PHP配置中工作。数组键可以是数字,也可以按标题行中给定的字段命名。希望这有帮助

    function SW_ImplodeCSV(array $rows, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
    // SW_ImplodeCSV - returns 2D array as string of csv(MS Excel .CSV supported)
    // AUTHOR: tgearin2@gmail.com
    // RELEASED: 9/21/13 BETA
      { $r=1; $row=array(); $fields=array(); $csv="";
        $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
        $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

        if($mode=='EXCEL')// escape code = ""
         { $delim=','; $enclos='"'; $rowbr="\r\n"; }
        else //mode=STANDARD all fields enclosed
           { $delim=','; $enclos='"'; $rowbr="\r\n"; }

          $csv=""; $i=-1; $i2=0; $imax=count($rows);

          while( $i < $imax )
          {
            // get field names
            if($i == -1)
             { $row=$rows[0];
               if($fmt=='2D_FIELDNAME_ARRAY')
                { $i2=0; $i2max=count($row);
                  while( list($k, $v) = each($row) )
                   { $fields[$i2]=$k;
                     $i2++;
                   }
                }
               else //if($fmt='2D_NUMBERED_ARRAY')
                { $i2=0; $i2max=(count($rows[0]));
                  while($i2<$i2max)
                   { $fields[$i2]=$i2;
                     $i2++;
                   }
                }

               if($headerrow==true) { $row=$fields; }
               else                 { $i=0; $row=$rows[0];}
             }
            else
             { $row=$rows[$i];
             }

            $i2=0;  $i2max=count($row); 
            while($i2 < $i2max)// numeric loop (order really matters here)
            //while( list($k, $v) = each($row) )
             { if($i2 != 0) $csv=$csv.$delim;

               $v=$row[$fields[$i2]];

               if($mode=='EXCEL') //EXCEL 2quote escapes
                    { $newv = '"'.(str_replace('"', '""', $v)).'"'; }
               else  //STANDARD
                    { $newv = '"'.(str_replace($escapes2, $escapes, $v)).'"'; }
               $csv=$csv.$newv;
               $i2++;
             }

            $csv=$csv."\r\n";

            $i++;
          }

         return $csv;
       }

    function SW_ExplodeCSV($csv, $headerrow=true, $mode='EXCEL', $fmt='2D_FIELDNAME_ARRAY')
     { // SW_ExplodeCSV - parses CSV into 2D array(MS Excel .CSV supported)
       // AUTHOR: tgearin2@gmail.com
       // RELEASED: 9/21/13 BETA
       //SWMessage("SW_ExplodeCSV() - CALLED HERE -");
       $rows=array(); $row=array(); $fields=array();// rows = array of arrays

       //escape code = '\'
       $escapes=array('\r', '\n', '\t', '\\', '\"');  //two byte escape codes
       $escapes2=array("\r", "\n", "\t", "\\", "\""); //actual code

       if($mode=='EXCEL')
        {// escape code = ""
          $delim=','; $enclos='"'; $esc_enclos='""'; $rowbr="\r\n";
        }
       else //mode=STANDARD 
        {// all fields enclosed
          $delim=','; $enclos='"'; $rowbr="\r\n";
        }

       $indxf=0; $indxl=0; $encindxf=0; $encindxl=0; $enc=0; $enc1=0; $enc2=0; $brk1=0; $rowindxf=0; $rowindxl=0; $encflg=0;
       $rowcnt=0; $colcnt=0; $rowflg=0; $colflg=0; $cell="";
       $headerflg=0; $quotedflg=0;
       $i=0; $i2=0; $imax=strlen($csv);   

       while($indxf < $imax)
         {
           //find first *possible* cell delimiters
           $indxl=strpos($csv, $delim, $indxf);  if($indxl===false) { $indxl=$imax; }
           $encindxf=strpos($csv, $enclos, $indxf); if($encindxf===false) { $encindxf=$imax; }//first open quote
           $rowindxl=strpos($csv, $rowbr, $indxf); if($rowindxl===false) { $rowindxl=$imax; }

           if(($encindxf>$indxl)||($encindxf>$rowindxl))
            { $quoteflg=0; $encindxf=$imax; $encindxl=$imax;
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }
           else 
            { //find cell enclosure area (and real cell delimiter)
              $quoteflg=1;
              $enc=$encindxf; 
              while($enc<$indxl) //$enc = next open quote
               {// loop till unquoted delim. is found
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//close quote
                 $encindxl=$enc; //last close quote
                 $indxl=strpos($csv, $delim, $enc+1); if($indxl===false)  { $indxl=$imax; }//last delim.
                 $enc=strpos($csv, $enclos, $enc+1); if($enc===false) { $enc=$imax; }//open quote
                 if(($indxl==$imax)||($enc==$imax)) break;
               }
              $rowindxl=strpos($csv, $rowbr, $enc+1); if($rowindxl===false) { $rowindxl=$imax; }
              if($rowindxl<$indxl) { $indxl=$rowindxl; $rowflg=1; }
            }

           if($quoteflg==0)
            { //no enclosured content - take as is
              $colflg=1;
              //get cell 
             // $cell=substr($csv, $indxf, ($indxl-$indxf)-1);
              $cell=substr($csv, $indxf, ($indxl-$indxf));
            }
           else// if($rowindxl > $encindxf)
            { // cell enclosed
              $colflg=1;

             //get cell - decode cell content
              $cell=substr($csv, $encindxf+1, ($encindxl-$encindxf)-1);

              if($mode=='EXCEL') //remove EXCEL 2quote escapes
                { $cell=str_replace($esc_enclos, $enclos, $cell);
                }
              else //remove STANDARD esc. sceme
                { $cell=str_replace($escapes, $escapes2, $cell);
                }
            }

           if($colflg)
            {// read cell into array
              if( ($fmt=='2D_FIELDNAME_ARRAY') && ($headerflg==1) )
               { $row[$fields[$colcnt]]=$cell; }
              else if(($fmt=='2D_NUMBERED_ARRAY')||($headerflg==0))
               { $row[$colcnt]=$cell; } //$rows[$rowcnt][$colcnt] = $cell;

              $colcnt++; $colflg=0; $cell="";
              $indxf=$indxl+1;//strlen($delim);
            }
           if($rowflg)
            {// read row into big array
              if(($headerrow) && ($headerflg==0))
                {  $fields=$row;
                   $row=array();
                   $headerflg=1;
                }
              else
                { $rows[$rowcnt]=$row;
                  $row=array();
                  $rowcnt++; 
                }
               $colcnt=0; $rowflg=0; $cell="";
               $rowindxf=$rowindxl+2;//strlen($rowbr);
               $indxf=$rowindxf;
            }

           $i++;
           //SWMessage("SW_ExplodeCSV() - colcnt = ".$colcnt."   rowcnt = ".$rowcnt."   indxf = ".$indxf."   indxl = ".$indxl."   rowindxf = ".$rowindxf);
           //if($i>20) break;
         }

       return $rows;
     }
函数SW\u introdecsv(数组$rows,$headerrow=true,$mode='EXCEL',$fmt='2D\u FIELDNAME\u array')
//SW_内爆csv-以csv字符串形式返回2D数组(支持MS Excel.csv)
//作者:tgearin2@gmail.com
//发布日期:2013年9月21日测试版
{$r=1;$row=array();$fields=array();$csv=”“;
$escapes=array('\r'、'\n'、'\t'、'\\'、'\');//两字节转义码
$escapes2=数组(“\r”、“\n”、“\t”、“\\”、“\\”);//实际代码
如果($mode=='EXCEL')//escape code=“”
{$delim=',';$enclose='”;$rowbr=“\r\n”;}
else//mode=标准所有封闭字段
{$delim=',';$enclose='”;$rowbr=“\r\n”;}
$csv=“”;$i=-1;$i2=0;$imax=count($rows);
而($i<$imax)
{
//获取字段名
如果($i==-1)
{$row=$rows[0];
如果($fmt=='2D\u字段名\u数组')
{$i2=0;$i2max=count($row);
while(列表($k,$v)=每个($row))
{$fields[$i2]=$k;
$i2++;
}
}
else//if($fmt='2D\u编号\u数组')
{$i2=0;$i2max=(count($rows[0]);

while($i2tanks mark)。但是您能告诉我一些关于如何逐行读取csv文件或如何写入csv文件的详细信息吗?您也可以使用以下语法:
$objWriter=new PHPExcel_Writer_csv($objPHPExcel);
With
require_once'[your_libs]/PHPExcel/Writer/CSV.php';
一旦CSV编写器出现,您就不需要真正要求它:当您创建新的PHPExcel\u Writer\u CSV($objPHPExcel)时,自动加载程序应该自动包含它政府提供了糟糕的文件developer@kratos-天啊,谢谢…那么您将如何记录它?如何改进文档?人们何时才能摆脱负面批评并开始尝试积极改变?这不使用PHPExcel,这是要求的。注意:是PHPExcel的下一个版本。请参阅