大家帮忙优化下吧
getletter方法是把数组的索引转成excel的表头
// 数字转字母
function getletter($num) {
$str = $num;
$num = intval($num);
if ($num $ret = chr(ord('a') + intval($str) - 1);
} else {
$first_str = chr(ord('a') + intval(floor($num / 26)) - 1);
$second_str = chr(ord('a') + intval($num % 26) - 1);
if ($num % 26 == 0){
$first_str = chr(ord('a') + intval(floor($num / 26)) - 2);
$second_str = chr(ord('a') + intval($num % 26) + 25);
}
$ret = $first_str.$second_str;
}
return $ret;
}
// excel 导入
/**
* 导入excel到数据库
* @param string $db 数据库表名
* @param path string 文件名(路径)
* @return boolean
*/
function excelimport($db, $file) {
import(org.util.phpexcel);
$phpexcel = new phpexcel();
$phpreader = new \phpexcel_reader_excel2007();
if (!$phpreader->canread($file)) {
$phpreader = new \phpexcel_reader_excel5();
if (!$phpreader->canread($file)){
return false;
}
}
$e = $phpreader->load($file);
$cur = $e->getsheet(0); // 读取第一个表
$end = $cur->gethighestcolumn(); // 获得最大的列数
$line = $cur->gethighestrow(); // 获得最大总行数
// 获取数据数组
$info = array();
for ($row = 1; $row for ($column = 'a'; $column $val = $cur->getcellbycolumnandrow(ord($column) - 65, $row)->getvalue();
$info[$row][] = $val;
}
}
$db = m($db);
$data = array();
for ($i = 2; $i for ($j = 0; $j for ($k = 0; $k $data[$i][$info[1][$k]] = $info[$i][$k];
}
}
}
$datalist = array_values($data);
$result = $db->addall($datalist);
// echo $db->getlastsql();exit;
if ($result) {
return true;
}
return false;
}
// 导出excel
/**
* 导出excel方法
* @param array $data 需要导出的数据
* @param array $title excel表头
* @param string $name 导出后的文件名
*/
function excelexport ($data, $title=null, $name=null) {
import(org.util.phpexcel);
$phpexcel = new phpexcel();
if(!is_null($title)){
array_unshift($data, $title);
}
if(is_null($name)){
$name = time();
}
foreach ($data as $k => $v) {
for ($i = 1; $i $tr = getletter($i).($k+1);
if ($value == null) {
$value = '';
}
$buffer[$tr]=array_values($v)[$i-1];
$phpexcel->getactivesheet()->setcellvalue($tr, array_values($v)[$i-1]);
}
}
$phpexcel->setactivesheetindex(0);
header('content-type: application/vnd.ms-excel');
header('content-disposition: attachment;filename=' . $name . '.xls'); //文件名称
header('cache-control: max-age=0');
$result = phpexcel_iofactory::createwriter($phpexcel, 'excel2007');
$result->save('php://output');
}
ad:真正免费,域名+虚机+企业邮箱=0元