加入收藏 | 设为首页 | 会员中心 | 我要投稿 常州站长网 (https://www.0519zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

PHP怎么完成读取excel导入数据库?

发布时间:2021-12-23 16:46:34 所属栏目:PHP教程 来源:互联网
导读:PHP怎么实现读取excel导入数据库?这篇文文章主要介绍基于ThinkPHP 框架实现的读取excel导入数据库操作,下面分享了具体的实现代码,有需要的朋友可以参考一下。 入口文件中: require_once VENDOR_PATH.PHPExcel/PHPExcel/IOFactory.php; require_once VEND
   PHP怎么实现读取excel导入数据库?这篇文文章主要介绍基于ThinkPHP 框架实现的读取excel导入数据库操作,下面分享了具体的实现代码,有需要的朋友可以参考一下。
 
        入口文件中:
 
require_once VENDOR_PATH.'PHPExcel/PHPExcel/IOFactory.php';
require_once VENDOR_PATH.'PHPExcel/PHPExcel.php';
 
        PHP:
 
namespace HomeController;
class ExcelController extends CommonController
{
public function Import() {
// vendor('PHPExcel.PHPExcel.IOFactory');
vendor("PHPExcel.PHPExcel.PHPExcel");
vendor("PHPExcel.PHPExcel.Writer.Excel5");
vendor("PHPExcel.PHPExcel.Writer.Excel2007");
//$excel = new PHPExcel();
$fileName = './trans_rate.xlsx';
date_default_timezone_set('PRC');
// 读取excel文件
try {
$objPHPExcel = PHPExcel_IOFactory::load($fileName);
$inputFileType = PHPExcel_IOFactory::identify($fileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
// $objPHPExcel = $objReader->load($fileName);
// 确定要读取的sheet $sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// 获取一行的数据
// $phone_str = '';
for ($row = 3; $row <= $highestRow; $row++) {
 $row_data = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, NULL, TRUE, FALSE);
//获取excel表中一行的数组数据
//dump($row_data);
$row_data = $row_data[0];
$time = date('Y-m-d H:i:s', strtotime(trim($row_data[0])));
$start_province = trim($row_data[1]);
$start_city = trim($row_data[2]);
...
// $phone_str .= '"' . $phone . '",';
$where['phone'] = $phone;
$id_arr = M(数据表名)->where($where)->getField('id');
$user_id = !empty($id_arr) ? $id_arr : 0;
$fields[] = [
'数据表字段' => $user_id,//用户id
          ...
           ];
}
// dump($fields);
$rate_add = M(数据表名)->addAll($fields);
dump($rate_add);
echo M()->getLastSql();
if (!(0 < $rate_add)) {
CommonController::logProfile('添加excel数据,SQL:' . M()->getLastSql()); $this->endBack(0); }
// echo $phone_str . '<br />';
// dump($user_id);
} catch (Exception $e) {
die('加载文件发生错误:"' . pathinfo($fileName, PATHINFO_BASENAME) . '": ' . $e->getMessage()); } }}

(编辑:常州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读