使用PHP将(xls,xlsx)转换为CSV后再上传

6

当用户点击更新按钮时,我正在尝试将Excel文件转换为CSV。

当我上传一个Excel文件到文件夹中时,使用PHPExcel获取该文件并读取所有数据并将其转换为CSV,则会起作用。

以下是代码。

<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <?php
    ini_set("display_errors", "1");
    ini_set("memory_limit", "-1");
    ini_set("max_execution_time", "-1");
    error_reporting(1);

    require_once "PHPExcel.php";
    $dir = "../excel2csv/";                 // Main Directory Name 
    $file_arr = array();
    $file_ext_arr = array('xls','xlsx');            // Valid Extensions of Excel File

    // From Directory get only Excel Files in Array
    if(is_dir($dir))
    {
        if($dh = opendir($dir))
        {
            while(($file = readdir($dh)) !== false)
            {
                $info = new SplFileInfo($file);
                $ext = $info->getExtension();           // Get Extension of Current File
                if(in_array($ext,$file_ext_arr))
                {
                    array_push($file_arr, $file);
                }
            }
            closedir($dh);
        }
    }

    // Make CSV File 
    $fp = fopen('file.csv', 'a');
    $list = array();

    foreach($file_arr as $val)
    {
        $arr_data = array();
        $objPHPExcel = PHPExcel_IOFactory::load($dir . $val);
        $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
        foreach($cell_collection as $cell)
        {
            $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
            $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
            $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
            //header will / should be in row 1 only. of course this can be modified to suit your need.
            // Skip Rows From Top if you have header in Excel then Change 0 to 1
            if($row == 0)
            {
                $header[$row][$column] = $data_value;
            }
            else
            {
                $arr_data[$row]['row'] = $row;
                $arr_data[$row][$column] = $data_value;
            }
        }
        $data = $arr_data;
        foreach($data as $val1)
        {
            $num_col = sizeof($val1) - 1;  // get number of columns in Excel 
            break;
        }
        $lwrcol=array();    
        foreach($data as $val2)
        {
            $alphaArr = range('A','Z');
            $colArr = range('A',$alphaArr[$num_col - 1]);

            foreach($colArr as $col)
            {
                $lwrcol[$col] = isset($val2[$col]) ? utf8_decode($val2[$col]) : "";
                fwrite($fp,$lwrcol[$col].",");
            }
            fwrite($fp,"\n");   
        }
        chmod(getcwd()."/file.csv", 0777);
    }
    fclose($fp);
    ?>
</html>

在以上代码中,首先我从文件夹中找到所有的Excel文件并生成一个file.csv文件。
我的目的是当用户在<input type="file" name="upload"/>选择任何文件并点击上传按钮后,在后端处理之前先将Excel文件转换为CSV文件。

据我所见,您的代码可以将 Excel 转换为 CSV,但您没有编写用于首先从 input 上传的代码。对吗? - Manwal
所有这些代码都在 <form action="file.php" method="post"> 中。 - Sahil Patel
1个回答

1
我看到你的代码可以保存CSV中的Excel数据。但首先你需要从FORM上传,然后再进行转换。所以你需要做的是:
首先,你需要为Form编写HTML,并在POST文件存在时首先上传文件。请查看以下代码片段:
<html>
    <head>
        <meta charset="UTF-8">
    </head>
    <?php
    ini_set("display_errors", "1");
    ini_set("memory_limit", "-1");
    ini_set("max_execution_time", "-1");
    error_reporting(1);


    require_once "PHPExcel.php";
    $dir = "../excel2csv/";                 // Main Directory Name 
    $file_arr = array();
    $file_ext_arr = array('xls','xlsx');            // Valid Extensions of Excel File



    if(!empty($_FILES)) {

        //uploading file first
        $info = pathinfo($_FILES['userFile']['name']);
        $ext = $info['extension']; // get the extension of the file
        $newname = "excelfile.".$ext; 

        $target = $dir.$newname;
        move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);

        //upload finish  wiring csv file now
        writecsv();

    }

    function wirtecsv(){
        // From Directory get only Excel Files in Array
        if(is_dir($dir))
        {
            if($dh = opendir($dir))
            {
                while(($file = readdir($dh)) !== false)
                {
                    $info = new SplFileInfo($file);
                    $ext = $info->getExtension();           // Get Extension of Current File
                    if(in_array($ext,$file_ext_arr))
                    {
                        array_push($file_arr, $file);
                    }
                }
                closedir($dh);
            }
        }

        // Make CSV File 
        $fp = fopen('file.csv', 'a');
        $list = array();

        foreach($file_arr as $val)
        {
            $arr_data = array();
            $objPHPExcel = PHPExcel_IOFactory::load($dir . $val);
            $cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
            foreach($cell_collection as $cell)
            {
                $column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
                $row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
                $data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
                //header will / should be in row 1 only. of course this can be modified to suit your need.
                // Skip Rows From Top if you have header in Excel then Change 0 to 1
                if($row == 0)
                {
                    $header[$row][$column] = $data_value;
                }
                else
                {
                    $arr_data[$row]['row'] = $row;
                    $arr_data[$row][$column] = $data_value;
                }
            }
            $data = $arr_data;
            foreach($data as $val1)
            {
                $num_col = sizeof($val1) - 1;  // get number of columns in Excel 
                break;
            }
            $lwrcol=array();    
            foreach($data as $val2)
            {
                $alphaArr = range('A','Z');
                $colArr = range('A',$alphaArr[$num_col - 1]);

                foreach($colArr as $col)
                {
                    $lwrcol[$col] = isset($val2[$col]) ? utf8_decode($val2[$col]) : "";
                    fwrite($fp,$lwrcol[$col].",");
                }
                fwrite($fp,"\n");   
            }
            chmod(getcwd()."/file.csv", 0777);
        }
        fclose($fp);
    }
    ?>


    <form action='' method='POST' enctype='multipart/form-data'>
    <input type='file' name='userFile'><br>
    <input type='submit' name='upload_btn' value='upload'>
    </form>
</html>

我不想在任何文件夹中移动文件。我希望在上传到服务器之前将Excel文件转换为CSV文件。 当用户选择任何Excel文件并单击“上传”按钮时,首先要进行的处理是将Excel文件转换为CSV文件,然后将该文件上传到“上传”文件夹中,以便在另一个过程中使用。 - Sahil Patel
它正在显示空白页面。 - Sri P
@SriP 我现在不知道空白页面的实际原因。为此,您需要逐步调试代码。 - Manwal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接