以前写了一篇关于PHP用PHPExcel导出MySQL数据到Excel表格 的文章。现在再写一篇PHP用PHPExcel导入Excel表格的数据到MySQL的文章,作为姊妹篇。
代码如下:
服务端:
//上传方法
public function upload()
{
header("Content-Type:text/html;charset=utf-8");
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728;// 设置附件上传大小
$upload->exts = array(‘xls‘, ‘xlsx‘);// 设置附件上传类
$upload->savePath = ‘/‘; // 设置附件上传目录
// 上传文件
$info = $upload->uploadOne($_FILES[‘excelData‘]);
$filename = ‘./Uploads‘ . $info[‘savepath‘] . $info[‘savename‘];
$exts = $info[‘ext‘];
if (!$info) { // 上传错误提示错误信息
$this->error($upload->getError());
} else {// 上传成功
$this->data_import($filename, $exts);
}
}
//导入数据方法
protected function data_import($filename, $exts = ‘xls‘)
{
//导入PHPExcel类库,因为PHPExcel没有用命名空间,只能inport导入
import("Org.Util.PHPExcel");
//创建PHPExcel对象,注意,不能少了 $PHPExcel = new \PHPExcel();
//如果excel文件后缀名为.xls,导入这个类
if ($exts == ‘xls‘) {
import("Org.Util.PHPExcel.Reader.Excel5");
$PHPReader = new \PHPExcel_Reader_Excel5();
} else if ($exts == ‘xlsx‘) {
import("Org.Util.PHPExcel.Reader.Excel2007");
$PHPReader = new \PHPExcel_Reader_Excel2007();
}
//载入文件
$PHPExcel = $PHPReader->load($filename);
//获取表中的第一个工作表,如果要获取第二个,把0改为1,依次类推
$currentSheet = $PHPExcel->getSheet(0);
//获取总列数
$allColumn = $currentSheet->getHighestColumn();
//获取总行数
$allRow = $currentSheet->getHighestRow();
//循环获取表中的数据,$currentRow表示当前行,从哪行开始读取数据,索引值从0开始
for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
//从哪列开始,A表示第一列
for ($currentColumn = ‘A‘; $currentColumn <= $allColumn; $currentColumn++) {
//数据坐标
$address = $currentColumn . $currentRow;
//读取到的数据,保存到数组$arr中
$cell = $currentSheet->getCell($address)->getValue();
if ($cell instanceof PHPExcel_RichText) {
$cell = $cell->__toString();
}
$data[$currentRow][$currentColumn] = $cell;
}
}
if (is_file($filename)) {
unlink($filename);
}
$this->save_import($data);
}
//保存导入数据
public function save_import($data)
{
$result = 1;
$model = new UserModel();
foreach ($data as $k => $v) {
if ($k >= 2) { //一般第一行是列名
//do something
$id = $model->addUser(array(‘alias‘ => trim($v[‘A‘]),‘token‘=>$k, ‘pass‘ => strtoupper(md5(trim($v[‘B‘]))), ‘create_time‘ => time()));
if (!$id) {
$result = 0;
exit($v);
}
}
}
if (false !== $result || 0 !== $result) {
$this->success(‘导入成功‘);
} else {
$this->error(‘导入失败‘);
}
}
客户端:
<form class="layui-form table table-condensed" action="{:U(‘upload‘)}" method="post" enctype="multipart/form-data">
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label" style="width: 132px">Excel表格:</label>
<div class="layui-input-inline" style="">
<input type="file" name="excelData" value="" datatype="*4-50" nullmsg="请填写!" errormsg="不能少于4个字符大于50个汉字"/>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline layui-form-select">
<input type="submit" class="btn btn-primary Sub" value="导入" />
</div>
</div>
</div>
</form>