excel导入导出

//

第一步首先建立一个表单

//

excel导入代码编写


load($uploadfile); 
        $sheet = $objPHPExcel->getSheet(0); 
        $highestRow = $sheet->getHighestRow();           //取得总行数 
        $highestColumn = $sheet->getHighestColumn(); //取得总列数
		 /* 第二种方法*/
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow(); 
        //echo 'highestRow='.$highestRow;
        echo "
"; $highestColumn = $objWorksheet->getHighestColumn(); $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//总列数 // echo 'highestColumnIndex='.$highestColumnIndex; echo "
"; $headtitle=array(); /***********连接数据库**********/ $pdo=new PDO("mysql:host=127.0.0.1;dbname=zong","root","song123",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';")); //$row不能为第一行,因为第一行是字段名 for ($row = 2;$row <= $highestRow;$row++) { $strs=array(); //注意highestColumnIndex的列数索引从0开始 for ($col = 0;$col < $highestColumnIndex;$col++) { $strs[$col] =$objWorksheet->getCellByColumnAndRow($col, $row)->getValue(); //print_r($strs);die; } //print_r($strs);die; $sql = "INSERT INTO news(`title`, `time`, `content`, `s_id`) VALUES ( '{$strs[1]}', '{$strs[2]}', '{$strs[3]}', '{$strs[4]}')"; if(!$pdo->query($sql)) { return false; echo "sql语句有误!!!!!!"; } } $msg = "你成功了,真牛逼"; } else { $msg = "导入失败!"; } return $msg; }


//

excel导出编码



getActiveSheet()->setCellValue('A1', 'id'); 
$resultPHPExcel->getActiveSheet()->setCellValue('B1', 'title'); 
$resultPHPExcel->getActiveSheet()->setCellValue('C1', 'time'); 
$resultPHPExcel->getActiveSheet()->setCellValue('D1', 'content'); 
$resultPHPExcel->getActiveSheet()->setCellValue('E1', 's_id'); 
//连接数据库
$pdo=new PDO("mysql:host=127.0.0.1;dbname=zong","root","song123",array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';"));
$rs = $pdo->query("SELECT * FROM news");
$i = 2; 
foreach($rs as $item){ 
$resultPHPExcel->getActiveSheet()->setCellValue('A' . $i, $item['id']); 
$resultPHPExcel->getActiveSheet()->setCellValue('B' . $i, $item['title']); 
$resultPHPExcel->getActiveSheet()->setCellValue('C' . $i, $item['time']); 
$resultPHPExcel->getActiveSheet()->setCellValue('D' . $i, $item['content']); 
$resultPHPExcel->getActiveSheet()->setCellValue('E' . $i, $item['s_id']); 
$i ++; 
}
//设置导出文件名 
$time = time();
$outputFileName = $time.'.xls'; 
$xlsWriter = new PHPExcel_Writer_Excel5($resultPHPExcel); 
//ob_start(); ob_flush(); 
header("Content-Type: application/force-download"); 
header("Content-Type: application/octet-stream"); 
header("Content-Type: application/download"); 
header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 
header("Content-Transfer-Encoding: binary"); 
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Pragma: no-cache"); 
$xlsWriter->save( "php://output" );


你可能感兴趣的:(php)