PHP-Excel读取导入Excel数据到数据库(2003,2007通用)使用方法

下载地址

http://phpexcel.codeplex.com/

使用案例

<?php
header("Content-type: text/html; charset=utf-8");
require_once 'phpexcel.php';
require_once 'PHPExcel\IOFactory.php';
require_once 'PHPExcel\Reader\Excel2007.php';
$uploadfile='data.xlsx';

$objReader = PHPExcel_IOFactory::createReader('Excel2007');/*Excel5 for 2003 excel2007 for 2007*/
$objPHPExcel = $objReader->load($uploadfile); //Excel 路径
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); // 取得总行数
$highestColumn = $sheet->getHighestColumn(); // 取得总列数
/*方法一*/
$strs=array();
for ($j=1;$j<=$highestRow;$j++){//从第一行开始读取数据
	/*注销上一行读取数据*/
	unset($str);
	unset($strs);
	for($k='A';$k<=$highestColumn;$k++){//从A列读取数据
		//实测在excel中,如果某单元格的值包含了||||||导入的数据会为空                     
		 $str .=$objPHPExcel->getActiveSheet()->getCell("$k$j")->getValue().'||||||';//读取单元格
	}
	//explode:函数把字符串分割为数组。            
	$strs = explode("||||||",$str);
	$sql = "INSERT INTO te() VALUES ( '{$strs[0]}','{$strs[1]}', '{$strs[2]}','{$strs[3]}','{$strs[4]}')";
	echo $sql.'<br>';
}
/*方法二【推荐】*/
$objWorksheet = $objPHPExcel->getActiveSheet();        
$highestRow = $objWorksheet->getHighestRow();   // 取得总行数     
$highestColumn = $objWorksheet->getHighestColumn();        
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数

for ($row = 1;$row <= $highestRow;$row++)         {
	$strs=array();
	//注意highestColumnIndex的列数索引从0开始
	for ($col = 0;$col < $highestColumnIndex;$col++)            {
		$strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
	}
	print_r($strs);
}
?>


输出效果如下:

INSERT INTO te() VALUES ( '1','2', '3','4','5')<br>INSERT INTO te() VALUES ( '11','22', '','','')<br>INSERT INTO te() VALUES ( '111','222', '','','')<br>INSERT INTO te() VALUES ( '1111','2222', '','','')<br>INSERT INTO te() VALUES ( '11111','22222', '','','')<br>Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
)
Array
(
    [0] => 11
    [1] => 22
    [2] => 
    [3] => 
    [4] => 
    [5] => 
)
Array
(
    [0] => 111
    [1] => 222
    [2] => 
    [3] => 
    [4] => 
    [5] => 
)
Array
(
    [0] => 1111
    [1] => 2222
    [2] => 
    [3] => 
    [4] => 
    [5] => 
)
Array
(
    [0] => 11111
    [1] => 22222
    [2] => 
    [3] => 
    [4] => 
    [5] => 
)


 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值