Home  >  Article  >  Backend Development  >  How to convert php xls to csv

How to convert php xls to csv

藏色散人
藏色散人Original
2020-10-19 11:29:462366browse

php xls to csv method: first create a PHP sample file; then import "PHPExcel.php"; then list all xls files, check and submit to "$_POST"; finally use the getCsv method Just convert xls to csv.

How to convert php xls to csv

Recommended: "PHP Video Tutorial"

PHPExcle converts xls files to csv files

When importing excel into the database, the data may appear as "= a certain cell" (=A3), so first convert the .xls file to a .csv file, and then import the csv file into the database.

<?php 
    header("Content-Type:text/html;charset=utf-8");
    require_once &#39;PHPExcel/PHPExcel.php&#39;; 
    $d = dir(&#39;xls/&#39;);
        while (($file = $d->read()) !== false){
            if(substr(strrchr($file, &#39;.&#39;), 1) == &#39;xls&#39;){
                $arr[] = $file; 
            }
        }
    //把所有xls文件列出列表,勾选提交到这边$_POST
        foreach($_POST as $k => $item){
            foreach($item as $v){
                //只获取文件名
                $file = str_replace(&#39;.xls&#39;,&#39;&#39;,$arr[$v]);
                getCsv($file);
            }
        }
    function getCsv($file){
        $filename = "xls/".$file.".xls";
        $objReader = new PHPExcel_Reader_Excel5();
        //$objReader = PHPExcel_IOFactory::createReader(&#39;Excel5&#39;);
        $objPHPExcel = $objReader->load($filename);
        //$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, &#39;CSV&#39;);
        $objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
        $objWriter->save(str_replace(&#39;.xls&#39;, &#39;.csv&#39;,$filename));
        $root = "xls/".$file.".csv";
        $newRoot=&#39;csv/&#39;.$file.&#39;.csv&#39;; //新目录
        copy($root,$newRoot); //拷贝到新目录
        unlink($root); //删除旧目录下的文件
    } 
?>

The above is the detailed content of How to convert php xls to csv. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn