2015-11-19 8 views
2

У меня есть проблема преобразования файлов CSV в feom XLSX формат:PHPExcel CSV для XLSX

index.php

<?php 
if (!isset($_FILES["file"])) 
{ 
?> 
<html> 
    <body> 
     <h1>Convert CSV to XLSX</h1> 
     <form action="index.php" method="post" enctype="multipart/form-data"> 
      <input type="file" name="file"/> 
      <input type="submit"/> 
     </form> 
    </body> 
</html> 
<?php 
    exit; 
} 

//obtain PHPExcel from http://phpexcel.codeplex.com 
require_once('Classes\PHPExcel.php'); 
require_once('CSVToExcelConverter.php'); 

if ($_FILES["file"]["error"] > 0) 
{ 
    echo "Error: " . $_FILES["file"]["error"]; 
    exit; 
} 

try 
{ 
    header('Content-type: application/ms-excel'); 
    header('Content-Disposition: attachment; filename='.'example.xlsx'); 

    CSVToExcelConverter::convert($_FILES['file']['tmp_name'], 'php://output'); 
} catch(Exception $e) { 
    echo $e->getMessage(); 
} 

CSVToExcelConverter.php

class CSVToExcelConverter 
{ 
    /** 
    * Read given csv file and write all rows to given xls file 
    * 
    * @param string $csv_file Resource path of the csv file 
    * @param string $xls_file Resource path of the excel file 
    * @param string $csv_enc Encoding of the csv file, use utf8 if null 
    * @throws Exception 
    */ 
    public static function convert($csv_file, $xls_file, $csv_enc=null) { 
     //set cache 
     $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_to_phpTemp; 
     PHPExcel_Settings::setCacheStorageMethod($cacheMethod); 

     //open csv file 
     $objReader = new PHPExcel_Reader_CSV(); 
     if ($csv_enc != null) 
      $objReader->setInputEncoding($csv_enc); 
     $objPHPExcel = $objReader->load($csv_file); 
     $in_sheet = $objPHPExcel->getActiveSheet(); 

     //open excel file 
     $objPHPExcel = new PHPExcel(); 
     $out_sheet = $objPHPExcel->getActiveSheet(); 

     //row index start from 1 
     $row_index = 0; 
     foreach ($in_sheet->getRowIterator() as $row) { 
      $row_index++; 
      $cellIterator = $row->getCellIterator(); 
      $cellIterator->setIterateOnlyExistingCells(false); 

      //column index start from 0 
      $column_index = -1; 
      foreach ($cellIterator as $cell) { 
       $column_index++; 
       $out_sheet->setCellValueByColumnAndRow($column_index, $row_index, $cell->getValue()); 
      } 
     } 

     //write excel file 
     $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
     $objWriter->save($xls_file); 
    } 
} 

формат CSV файла: CSV file opened with Excel

xlsx file I get after conversion

Basicaly Я хотел бы получить вывод, похожий на оригинальный файл csv, но в формате xmlx, как это сделать?

ответ

1

Разделитель по умолчанию для чтения CSV-файла в PHPExcel является запятой (,). В файле CSV используется нечто иное, кроме запятой - возможно, вкладка ("\t"), которая также обычно используется для таких файлов).

Если значения не являются запятой (и мы не можем сказать по изображению файла, просмотренного в MS Excel), тогда вы должны явно указать PHPExcel, что этот разделитель перед загрузкой.

например.

$objReader->setDelimiter("\t"); 
+0

Благодарим за ответ! Это сделало вещи для меня более ясными! – JustinasT

Смежные вопросы