首先从GitHub上下载 excel的相关类库
下载地址:
https://github.com/PHPOffice/PHPExcel以下是从excel中获取数据
1 6 * @version 1.01 7 */ 8 9 error_reporting(E_ALL);10 date_default_timezone_set('Asia/ShangHai');11 12 /** PHPExcel_IOFactory */13 require_once 'Classes/PHPExcel/IOFactory.php';14 15 // Check prerequisites16 if (!file_exists("report.xls")) {17 exit("not found report.xls.\n");18 }19 20 $reader = PHPExcel_IOFactory::createReader('Excel5'); //设置以Excel5格式(Excel97-2003工作簿)21 $PHPExcel = $reader->load("report.xls"); // 载入excel文件22 $sheet = $PHPExcel->getSheet(0); // 读取第一個工作表23 $highestRow = $sheet->getHighestRow(); // 取得总行数24 $highestColumm = $sheet->getHighestColumn(); // 取得总列数25 26 /** 循环读取每个单元格的数据 */27 for ($row = 1; $row <= $highestRow; $row++){ //行数是以第1行开始28 for ($column = 'A'; $column <= $highestColumm; $column++) { //列数是以A列开始29 $dataset[] = $sheet->getCell($column.$row)->getValue();30 echo $column.$row.":".$sheet->getCell($column.$row)->getValue()."";31 }32 }33 34 ?>
下面的是从将数据插入到excel中
1 getProperties()->setCreator("云舒")15 // ->setLastModifiedBy("云舒")16 // ->setTitle("产品URL导出")17 // ->setSubject("产品URL导出")18 // ->setDescription("产品URL导出")19 // ->setKeywords("产品URL导出");20 $objPHPExcel->setActiveSheetIndex(0);21 22 $cols = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';23 //设置www.jb51.net标题24 for($i=0,$length=count($title); $i<$length; $i++) {25 //echo $cols{$i}.'1';26 $objPHPExcel->getActiveSheet()->setCellValue($cols{$i}.'1', $title[$i]);27 }28 //设置标题样式29 $titleCount = count($title);30 $r = $cols{ 0}.'1';31 $c = $cols{$titleCount}.'1';32 $objPHPExcel->getActiveSheet()->getStyle("$r:$c")->applyFromArray(33 array(34 'font' => array(35 'bold' => true36 ),37 'alignment' => array(38 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,39 ),40 'borders' => array(41 'top' => array(42 'style' => PHPExcel_Style_Border::BORDER_THIN43 )44 ),45 'fill' => array(46 'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,47 'rotation' => 90,48 'startcolor' => array(49 'argb' => 'FFA0A0A0'50 ),51 'endcolor' => array(52 'argb' => 'FFFFFFFF'53 )54 )55 )56 );57 58 $i = 0;59 foreach($data as $d) { //这里用foreach,支持关联数组和数字索引数组60 $j = 0;61 foreach($d as $v) { //这里用foreach,支持关联数组和数字索引数组62 $objPHPExcel->getActiveSheet()->setCellValue($cols{$j}.($i+2), $v);63 $j++;64 }65 $i++;66 }67 // 生成2003excel格式的xls文件68 header('Content-Type: application/vnd.ms-excel');69 header('Content-Disposition: attachment;filename="'.$filename.'.xls"');70 header('Cache-Control: max-age=0');71 72 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');73 $objWriter->save('php://output');74 }75 76 77 78 79 80 //传递数组的形式进行 导出excel文件81 $array = array(82 array(1111,'名称','品牌','商品名','http://www.jb51.net'),83 array(1111,'名称','品牌','商品名','http://www.jb51.net'),84 array(1111,'名称','品牌','商品名','http://www.jb51.net'),85 array(1111,'名称','品牌','商品名','http://www.jb51.net'),86 array(1111,'名称','品牌','商品名','http://www.jb51.net'),87 );88 write_xls($array,array('商品id','供应商名称','品牌','商品名','URL'),'report');89 90 ?>