本篇文章给大家分享的内容是如何将phpexcel文件导入thinkphp3.2.3,有着一定的参考价值,有需要的朋友可以参考一下
1.首先,先下载phpexcel插件:
thinkphp版本:3.2.3
phpexcel版本:1.8
phpexcel 官方下载地址:https://github.com/phpoffice/phpexcel
2.解压后如下:
只要classes 文件夹,其它的没有什么用,将classes 文件夹名改成 phpexcel (自己任意起名)
3.将 phpexcel 文件下复制到thinkphp 中,位置如下
4.一切准备就绪,开如我们的征程吧。
前端代码:
<form action="{:u('index/upload')}" method="post" enctype="multipart/form-data">
<ul>
<li><input type="file" name="files" /></li>
<li><input type="submit" value="上传" /></li>
</ul>
</form>
后端代码(indexcontroller.class.php 中的 upload方法):
public function upload(){
if(isset($_files["files"]) && ($_files["files"]["error"] == 0)){
$result = importexecl($_files["files"]["tmp_name"]);
echo '<pre />';
print_r($result);
die;
}
}
其中 importexecl 写在公共方法中,位置如下
公共方法的代码如下:
function importexecl($file='', $sheet=0){
$file = iconv("utf-8", "gb2312", $file); //转码
if(empty($file) or !file_exists($file)) {
die('file not exists!');
}
vendor("phpexcel.phpexcel"); // 引入我们自己导入的文件
$objread = new phpexcel_reader_excel2007(); //建立reader对象
if(!$objread->canread($file)){
$objread = new phpexcel_reader_excel5();
if(!$objread->canread($file)){
die('no excel!');
}
}
$cellname = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
'x', 'y', 'z', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag', 'ah', 'ai',
'aj', 'ak', 'al', 'am', 'an', 'ao', 'ap', 'aq', 'ar', 'as', 'at', 'au',
'av', 'aw', 'ax', 'ay', 'az');
$obj = $objread->load($file); //建立excel对象
$currsheet = $obj->getsheet($sheet); //获取指定的sheet表
$columnh = $currsheet->gethighestcolumn(); //取得最大的列号
$columncnt = array_search($columnh, $cellname);
$rowcnt = $currsheet->gethighestrow(); //获取总行数
$data = array();
for($_row=1; $_row<=$rowcnt; $_row++){ //读取内容
for($_column=0; $_column<=$columncnt; $_column++){
$cellid = $cellname[$_column].$_row;
$cellvalue = $currsheet->getcell($cellid)->getvalue();
//$cellvalue = $currsheet->getcell($cellid)->getcalculatedvalue(); #获取公式计算的值
if($cellvalue instanceof phpexcel_richtext){ //富文本转换字符串
$cellvalue = $cellvalue->__tostring();
}
$data[$_row][$cellname[$_column]] = $cellvalue;
}
}
return $data;
}
5.最后上传 xls 文件,成功的话,打印如下:
6.最后,代码写的比较简单,文件类型,大小自己可以验证,我这里就不写了,以上代码亲测,没有问题。
以上就是如何将phpexcel文件导入thinkphp3.2.3的详细内容。