phpexcel实现导入内容到数据库中

本文介绍了一种使用PHPExcel库从Excel文件(.xlsx格式)中读取数据并将其加载到数据库的方法。通过设置PHP环境和PHPExcel库,可以实现对Excel文件的读取,并获取文件中的最高行数和列数,以便进一步处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<?php
02
/**
03
* phpexcel实例 导入数据库
04
* by www.jbxue.com
05
*/
06
error_reporting(E_ALL); //开启错误
07
set_time_limit(0); //脚本不超时
08
 
09
date_default_timezone_set('Europe/London'); //设置时间
10
 
11
/** Include path **/
12
set_include_path(get_include_path() . PATH_SEPARATOR . 'http://www.jbxue.com/../Classes/');//设置环境变量
13
 
14
/** PHPExcel_IOFactory */
15
include 'PHPExcel/IOFactory.php';
16
 
17
//$inputFileType = 'Excel5';    //这个是读 xls的
18
    $inputFileType = 'Excel2007';//这个是计xlsx的
19
//$inputFileName = './sampleData/example2.xls';
20
$inputFileName = './sampleData/book.xlsx';
21
 
22
        echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' using IOFactory with a defined reader type of ',$inputFileType,'<br />';
23
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);
24
        $objPHPExcel = $objReader->load($inputFileName);
25
        /*
26
        $sheet = $objPHPExcel->getSheet(0);
27
        $highestRow = $sheet->getHighestRow(); //取得总行数
28
        $highestColumn = $sheet->getHighestColumn(); //取得总列
29
        */   
30
        $objWorksheet = $objPHPExcel->getActiveSheet();//取得总行数
31
        $highestRow = $objWorksheet->getHighestRow();//取得总列数
32
 
33
        echo 'highestRow='.$highestRow;
34
        echo "<br>";
35
        $highestColumn = $objWorksheet->getHighestColumn();
36
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数
37
        echo 'highestColumnIndex='.$highestColumnIndex;
38
        echo "<br />";
39
        $headtitle=array();
40
        for ($row = 1;$row <= $highestRow;$row++)
41
        {
42
            $strs=array();
43
            //注意highestColumnIndex的列数索引从0开始
44
            for ($col = 0;$col < $highestColumnIndex;$col++)
45
            { 
46
                $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
47
            } 
48
              $info = array(
49
                      'word1'=>"$strs[0]",
50
                    'word2'=>"$strs[1]",
51
                    'word3'=>"$strs[2]",
52
                    'word4'=>"$strs[3]",
53
              );
54
              //引处可放置代码,写入数据库
55
              print_r($info);
56
              echo '<br />';
57
        }
58
?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值