Maison  >  Article  >  développement back-end  >  使用PHPExcel库

使用PHPExcel库

WBOY
WBOYoriginal
2016-07-25 08:42:24840parcourir

使用前请引入PHPExcel库

  1. /**
  2. * excel 写入,基于PHPExcel库
  3. * @param array $data
  4. * @param $file
  5. * @return bool
  6. * @throws PHPExcel_Exception
  7. *
  8. */
  9. function excel_insert(array $data,$file){
  10. // $data = [
  11. // '库房'=>[
  12. // ['库房编号','库房名词',1],
  13. // ['库房编号','库房名词',1],
  14. // ['库房编号','库房名词',1],
  15. // ['库房编号','库房名词',1],
  16. // ['库房编号','库房名词',1],
  17. // ],
  18. // '库房2'=>[
  19. // ['库房编号','库房名词',1],
  20. // ['库房编号','库房名词',1],
  21. // ['库房编号','库房名词',1],
  22. // ['库房编号','库房名词',1],
  23. // ['库房编号','库房名词',1],
  24. // ],
  25. // ];
  26. // excel_insert($data,'s.xlsx');
  27. if(!$data||!$file){
  28. return false;
  29. }
  30. $sheet_id = 0;
  31. //创建excel操作对象
  32. $objPHPExcel = new PHPExcel();
  33. //获得文件属性对象,给下文提供设置资源
  34. $objPHPExcel->getProperties()->setCreator("绵阳市碳素云信息技术有限责任公司")
  35. ->setLastModifiedBy("绵阳市碳素云信息技术有限责任公司")
  36. ->setTitle("Input_Goods_message")
  37. ->setSubject("主题1")
  38. ->setDescription("随便一个描述了")
  39. ->setKeywords("关键字 用空格分开")
  40. ->setCategory("分类 ");
  41. for($i=1;$i $objPHPExcel->addSheet(new PHPExcel_Worksheet($objPHPExcel,'sheet'.$i));
  42. }
  43. foreach($data as $sheetName => $sheetData){
  44. $Sheet = $objPHPExcel->setActiveSheetIndex($sheet_id);
  45. $Sheet->setTitle($sheetName);
  46. $insert_id = 1;
  47. foreach($sheetData as $rowData){
  48. if(is_array($rowData)&&$rowData){
  49. foreach($rowData as $id => $cellData){
  50. if(is_numeric($id)&&(is_string($cellData)||is_numeric($cellData))){
  51. $Sheet->setCellValue(chr(65+$id).$insert_id,$cellData);
  52. }else{
  53. return false;
  54. }
  55. }
  56. $insert_id++;
  57. }else{
  58. return false;
  59. }
  60. }
  61. $sheet_id++;
  62. }
  63. try{
  64. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  65. $objWriter->save($file);
  66. }catch (Exception $e){
  67. return false;
  68. }
  69. }
复制代码

使用方法:
  1. $data = [
  2. '库房'=>[
  3. ['库房编号','库房名词',1],
  4. ['库房编号','库房名词',1],
  5. ['库房编号','库房名词',1],
  6. ['库房编号','库房名词',1],
  7. ['库房编号','库房名词',1],
  8. ],
  9. '库房2'=>[
  10. ['库房编号','库房名词',1],
  11. ['库房编号','库房名词',1],
  12. ['库房编号','库房名词',1],
  13. ['库房编号','库房名词',1],
  14. ['库房编号','库房名词',1],
  15. ],
  16. ];
  17. excel_insert($data,'s.xlsx');
复制代码

PHPExcel


Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn