简体   繁体   English

PHPExcel CSV 到 XLSX

[英]PHPExcel CSV to XLSX

I have a problem converting file feom CSV to XLSX format:我在将 feom CSV 文件转换为 XLSX 格式时遇到问题:

Index.php索引.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 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 File format: CSV file opened with Excel CSV 文件格式:用 Excel 打开的 CSV 文件

xlsx file I get after conversion转换后我得到的 xlsx 文件

Basicaly I would like to get output similar to original csv file, but in xmlx format, how to do that?基本上我想得到类似于原始 csv 文件的输出,但是在 xmlx 格式中,如何做到这一点?

The "default" separator for reading a CSV file in PHPExcel is a comma ( , ).在 PHPExcel 中读取 CSV 文件的“默认”分隔符是逗号 ( , )。 Your CSV file is using something other than a comma - perhaps a tab ( "\\t" ), which is also commonly used for such files).您的 CSV 文件使用的不是逗号 - 可能是制表符( "\\t" ),这也常用于此类文件)。

If the values isn't a comma (and we can't tell from an image of the file viewed in MS Excel) then you have to tell PHPExcel explicitly what that separator is before loading.如果值不是逗号(并且我们无法从 MS Excel 中查看的文件图像中分辨出来),那么您必须在加载之前明确告诉 PHPExcel 该分隔符是什么。

eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM