我想在用户点击更新按钮时将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"/>
中的任何文件并点击UPLOAD按钮后,在后端第一个过程将Excel文件转换为CSV 之前它移动到上传文件夹
答案 0 :(得分:1)
我可以看到您的代码用于保存Excel
的{{1}}数据。但首先,您要先从CSV
上传,然后才能转换。所以你可以做的就是:
首先,您需要FORM
的HTML,如果有POST文件,则首先上传文件。请看下面的代码:
Form