這個是最近需要做的一個功能,在網上也查看了很多相關的文章,基本上大同小異,在這里整理一下。
一:首先是html部分
<html> <body> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" id="file" /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html>
二:就是去接收和處理上傳的文件了。php部分
//文件存放的路徑
$save_path = "/upload/";
//文件存放的文件夾
$save_files = $this->geturl();
這個是以年月日新建的文件夾,僅供參考。
//先檢查當前文件夾是否存在,如不存在,創建文件夾
function geturl()
{
$year = date('Y');
$month= date('m');
$day= date('d');
$str = $year.$month.$day;
if(strtoupper(substr(PHP_OS,0,3))=='WIN'){
$path = getcwd() . "/upload/".$str;
}else{
$path = "/mnt/erp/".$str;
}
if(!file_exists($path))//判斷文件夾是否存在
{
mkdir($path);
}
//return $path."/";
return $str."/";
}
//這個是上傳文件到需要保存的位置,
if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_path)) {
$error = "error|上傳文件錯誤.";
exit(0);
}
下面開始獲取你上傳的excel數據了
//獲取上傳表格的數據
$file_name = $save_path.$file_path; //獲取上傳文件的地址名稱
require_once APPPATH . 'views/IDC/config/PHPExcel.php';
require_once APPPATH . 'views/IDC/config/PHPExcel/IOFactory.php';
require_once APPPATH . 'views/IDC/config/PHPExcel/Cell.php';
$objReader = PHPExcel_IOFactory::createReader('excel2007'); //建立reader對象
$objPHPExcel = $objReader->load($file_name);
$sheet = $objPHPExcel->getSheet();
$highestRow = $sheet->getHighestDataRow(); // 取得總行數
$highestColumn_num = PHPExcel_Cell::columnIndexFromString($sheet->getHighestDataColumn()); //列數
//$columns = PHPExcel_Cell::getColumn($highestColumn_num);
$columns = array('A','B','C','D','E','F','G');
$arr_result = array();
$dealer_element = array();
for ($j = 2; $j <= $highestRow; $j++) {
for ($k = 0; $k < count($columns); $k++) {
//讀取單元格
$value = $objPHPExcel->getActiveSheet()->getCell($columns[$k] . $j)->getValue();//這個就是獲取每個單元格的值
$value = trim($value);
if (empty($value)) {
$value = NULL;
}
$dealer_element[$k] = $value;
//這里可以根據要求,做一些數據的驗證
}
$arr_result[$j] = $dealer_element;
}
echo json_encode($arr_result);
