通过PHPExcel将Excel表文件中数据导入数据库

时间:2021-10-13 07:57:49
 1 <?php
 2 header("Content-Type:text/html;charset=utf-8");
 3 include_once 'PHPExcel.php';
 4 include_once 'PHPExcel/IOFactory.php';
 5 
 6 set_time_limit(600);
 7 //文件的目录
 8 $dir = './files/';
 9 $array = scandir($dir);//列出指定路径中的文件和目录
10 $count = 3832;
11 $p = $_GET['p'];
12 if($p <= 1) {
13     $p = 1;
14 }
15 $countP = $p + 5;
16 $countP = $countP > $count ? $count : $countP;
17 
18 for($i = $p; $i<$countP; $i++) {
19     $reader = PHPExcel_IOFactory::createReader('Excel5');
20     // $resource = $dir . '3815.xls';
21     $resource = $dir . $i . '.xls';
22     //echo $resource;
23     $PHPExcel = $reader->load($resource); // 文件名称
24     $sheet = $PHPExcel->getSheetByName('低压线路');//文件下的一个sheet表
25     $highestRow = $sheet->getHighestRow(); // 取得总行数
26     //echo $highestRow.'<br>';
27     //连接数据库
28     $dsn = "mysql:host=localhost;dbname=data_info";
29     $username = "root";
30     $passwd = "";
31     $pdo = new PDO($dsn, $username, $passwd);
32     $pdo->query("SET NAMES utf8");
33 
34     for ($j = 4; $j <= $highestRow; $j++) {
35         //取出数据
36      //getCellByColumnAndRow(参数1,参数2)->getValue();      ————获取某行某列的数据值
37      //其中:  参数1:列的位置 参数2: 行的位置
38         $name = $sheet->getCellByColumnAndRow(3, $j)->getValue();
39         $id = $sheet->getCellByColumnAndRow(7, $j)->getValue();
40         $byq = $sheet->getCellByColumnAndRow(8, $j)->getValue();
41         $bz = $sheet->getCellByColumnAndRow(11, $j)->getValue();
42         $time = $sheet->getCellByColumnAndRow(13, $j)->getValue();
43         if ($name) {
44             $sql = "insert into low_line_copy(circuit_name, trans_id, trans_name, maintain_group, `time`) values
45         ('" . $name . "','" . $id . "','" . $byq . "','" . $bz . "','" . $time . "'); \n";
46             echo $sql . '<br>';
47             //指定数据存到文件中
48             file_put_contents('./a.txt', $i . ',' . $sql . "\r\n", FILE_APPEND);
49         }
50         //$pdo->exec($sql);
51     }
52     unset($reader);
53 }
54 ?>
55     <script>
56         //每页执行5条,之后跳转
57         location.href = "1.php?p=<?=($i);?>";
58     </script>