PHP 引用PHPExcel类 读取excel文件存入数据表的实现过程


header("Content-type:text/html;charset=utf-8");

include('conn.php');

require_once 'Classes/PHPExcel.php';

require_once 'Classes/PHPExcel/IOFactory.php';

require_once 'Classes/PHPExcel/Reader/Excel5.php';

$resource = 'upload_file/1.xlsx';

if (!file_exists($resource)) {

exit("$resource is not exists.\n");

}

$reader = PHPExcel_IOFactory::createReader('Excel5');

$PHPExcel = $reader->load($resource); // 文件名称

$sheet = $PHPExcel->getSheet(0); // 读取第一个工作表从0读起

$highestRow = $sheet->getHighestRow(); // 取得总行数

$highestColumn = $sheet->getHighestColumn(); // 取得总列数,不过是最大列的字母

$highestColumn = PHPExcel_Cell::columnIndexFromString($highestColumn); // 转换字母为对应的统计数字;

// getCellByColumnAndRow(0,1),第一列为0,第一行为1;

echo $highestRow . "、" . $highestColumn . "、" . $sheet->getCellByColumnAndRow(0, 2)->getCalculatedValue() . "(数量统计结束,换行)
";

// 每次读取一行,再在行中循环每列的数值

$excelArray = array();

for ($row = 2; $row <= $highestRow; $row++) {

$val = $sheet->getCellByColumnAndRow(0, $row)->getCalculatedValue();

if ($val == "") return;

for ($column = 1; $column < $highestColumn; $column++) {

$isDate = 0;

$isDate = PHPExcel_Shared_Date::isDateTime($sheet->getCellByColumnAndRow($column, $row));

$val = $sheet->getCellByColumnAndRow($column, $row)->getCalculatedValue();

$excelArray[$row][] = $val;

echo "" . $column . ")" . $val . "";

echo "
";

}

echo "
已读完第" . $row . "行数据:" . $excelArray[$row][3] . "


";

//在这儿使用SQL语句,取$excelArray[$row][3]、$excelArray[$row][4]、$excelArray[$row][5]存入数据库对应字段

//var_dump($excelArray);die;

$area_name = $excelArray[$row][0];

$company_id = $excelArray[$row][1];

$company_name = $excelArray[$row][2];

$line_type = $excelArray[$row][3];

$line_name = $excelArray[$row][4];

$fare = $excelArray[$row][5];

$departing_time = $excelArray[$row][6];

$journey_time = $excelArray[$row][7];

$notes = $excelArray[$row][8];

$is_active = $excelArray[$row][9];

$airport_name = $excelArray[$row][10];

$sql="insert into line_info (area_name,company_id,company_name,line_type,line_name,fare,departing_time,journey_time,notes,is_active,airport_name) values ('$area_name','$company_id','$company_name','$line_type','$line_name','$fare','$departing_time','$journey_time','$notes','$is_active','$airport_name')";

//echo $sql;die;

mysql_query("set names 'UTF-8'");

if (@mysql_query($sql))

{

echo "添加数据记录:" . $excelArray[$row][2] . "成功";

}else {

echo "company_id - > ". $company_id;

echo "失败";

}

}

你可能感兴趣的:(PHP 引用PHPExcel类 读取excel文件存入数据表的实现过程)