Thinkphp导入导出excel表
1、下载 phpreportexcl 的使用包 Excel 放在 THINKPHP 的程序包目录下第三方插件库 INC/THINKPHP/Vendor中 。
2、导出功能:
function export(){
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=stu_report_".date("Y-m-d").".xls");
header("Pragma: no-cache");
header("Expires: 0");
//导出xls 开始
$tag1 = iconv("UTF-8", "GB2312",'日期');
$tag2 = iconv("UTF-8", "GB2312",'学员姓名');
echo "$tag1\t$tag2\n";
$stu = M (‘stu’);
$arr = $stu -> select();
foreach($arr as $key=>$val){
$date = date('Y-m-d',$val['pay_time']);
$stu_name = iconv("UTF-8", "GB2312", $val['stuname']);
echo "$date\t$stu_name\n";
}
}
3、 导入功能:
确保导入的xls 中的字段和数据中的可以对号;
导入静态页面:
<script>
function import_check(){
var f_content = form1.file.value;
if(f_content==''){
alert('请选择您要上传的文件!');
return false;
}
var fileext=f_content.substring(f_content.lastIndexOf("."),f_content.length)
fileext=fileext.toLowerCase()
if (fileext!='.xls')
{
alert("对不起,导入数据格式必须是xls格式文件哦,请您调整格式后重新上传,谢谢 !");
return false;
}
}
</script>
<form id="form1" name="form1" enctype="multipart/form-data" action="/index.php/Admin/import" method="post">
<input name="file" type="file" id="file" size="50" />
<input type="submit" class='background_img' value="上传文档" style='margin-top:2px;' onclick="return import_check();"/>
</form>
导入页面处理方法:
if($_POST){
header("Content-type: text/html; charset=utf-8");
error_reporting(E_ALL ^ E_NOTICE);
$Import_TmpFile = $_FILES['file']['tmp_name'];
Vendor('Excel.reader'); //导入thinkphp 中第三方插件库
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read($Import_TmpFile);
$array =array();
for ($i = 1; $i < $data->sheets[0]['numRows']; $i++) {
for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {
$array[$i][$j] = $data->sheets[0]['cells'][$i+1][$j];
}
}
Print_r($array);
foreach( $array as $tmp){
$fmess = D ('a_fee_mess');
$fmess_add['stuname'] = $tmp['2'];
$fmess_add['fee'] = $tmp['3'];
$fmess_add['pay_time'] = strtotime(str_replace('/','-',$tmp[1]));
$fmess->add($fmess_add);
}
}
参考:http://gaoke0820.blog.163.com/blog/static/21664965201171265813216/