class ExcelAction extends Action {
//导出Excel文件
public function index(){
header("Content-Typ:text/html;charset=utf-8");
vendor('Excel.PHPExcel.Writer.IWriter');
vendor('Excel.PHPExcel.Writer.Excel5');
vendor('Excel.PHPExcel');
vendor('Excel.PHPExcel.IOFactory');
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setCellValue('A1', "编号");//设置列的值
$objPHPExcel->getActiveSheet()->setCellValue('B1', "姓名");//设置列的值
$objPHPExcel->getActiveSheet()->setCellValue('C1', "登录时间");//设置列的值
$arr=M('user')->order("id asc")->select();
$count = count($arr); //求出有多少行;
$i=2; //注意这是2;因为第一行我们已经设置了表头信息
for($j=0;$j<$count;$j++)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$i,$arr[$j]['id']) //注意这里没有分号结束
->setCellValue('B'.$i,$arr[$j]['username'])
->setCellValue('C'.$i,date('Y-m-d H:i:s',$arr[$j]['logintime']));
$i++;
}
$objPHPExcel->getActiveSheet(0)->setTitle('user');
$objPHPExcel->setActiveSheetIndex(0);
header('Content-Type:application/vnd.ms-excel');
header('Content-Disposition:attachment;filename="user.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
//导入Excel文件
public function importExcel(){
header("content-type:text/html;charset=utf-8");
vendor('Excel.PHPExcel');
vendor('Excel.PHPExcel.IOFactory');
vendor('Excel.PHPExcel.Reader.Excel5');
$objReader = new PHPExcel_Reader_Excel5;//注意和导出的类不一样哦
$objPHPExcel = $objReader->load('user.xls'); //上传的文件,或者是指定的文件
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow(); //取得总行数
$highestColumn = $sheet->getHighestColumn(); //取得总列数
for($j=2;$j<=$highestrow;$j++)
{
$name = $objPHPExcel->getActiveSheet()->getCell("B".$j)->getValue();//获取B列的值
$time = strtotime($objPHPExcel->getActiveSheet()->getCell("C".$j)->getValue());//获取C列的值
if(!M('user')->add(array('username'=>$name,'logintime'=>$time))){echo '失败';}
}
echo '成功';
}
}
?>
|