Blogger Information
Blog 87
fans 1
comment 0
visits 59141
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
office文件的导出导入
阿杰
Original
649 people have browsed it

一、导入excel

  • tp6导入excel文件使用phpoffice
  • 使用composer安装office
  1. composer require phpoffice/phpspreadsheet
  • 安装成功后项目的composer.json可以看到

  • 具体代码
  1. /**
  2. * 导入excel
  3. */
  4. public function importData(){
  5. // 接受文件上传
  6. $file = Request()->file('file');
  7. $savename = Filesystem::disk('public')->putFile('office',$file);
  8. // 获取文件后缀名
  9. $fileExtendName = substr(strrchr($savename, '.'), 1);
  10. // 有Xls和Xlsx格式两种
  11. if ($fileExtendName == 'xlsx') {
  12. // $objReader = IOFactory::createReader('Xlsx');
  13. $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
  14. } else {
  15. // $objReader = IOFactory::createReader('Xls');
  16. $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
  17. }
  18. $objReader->setReadDataOnly(TRUE);
  19. // 读取文件,tp6默认上传的文件,在runtime的相应目录下,可根据实际情况自己更改
  20. $objPHPExcel = $objReader->load(root_path() . '/public/storage/' . $savename);
  21. // 获取excel表中的对一张sheet
  22. $sheet = $objPHPExcel->getSheet(0);
  23. // 获取总行数
  24. $highestRow = $sheet->getHighestRow();
  25. // 获取总列数
  26. $highestColumn = $sheet->getHighestColumn();
  27. // 将列名转换成数字
  28. \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn);
  29. $lines = $highestRow - 1;
  30. if($lines <= 0){
  31. return Result::Error(0,'导入失败,文件内容不能为空!');
  32. }
  33. $data = array();
  34. for($j=2;$j<=$highestRow;$j++){
  35. $data[$j-2] = [
  36. 'name'=> trim($objPHPExcel->getActiveSheet()->getCell("A" . $j)->getValue()),
  37. 'price'=> trim($objPHPExcel->getActiveSheet()->getCell("B" . $j)->getValue()),
  38. ];
  39. }
  40. $result = Db::connect('mysql2')->table('goods')->insertAll($data);
  41. if($result){
  42. return Result::Success('','导入成功!');
  43. }else{
  44. return Result::Error(0,'导入失败!');
  45. }
  46. }

二、导出excel

  • 引入要用到的包
  1. use \PhpOffice\PhpSpreadsheet\Spreadsheet;
  2. use \PhpOffice\PhpSpreadsheet\IOFactory;
  • 具体代码
  1. /**
  2. * 导出excel
  3. */
  4. public function exportData(){
  5. // excel 模板下载
  6. $newExcel = new Spreadsheet(); //创建一个新的excel文档
  7. $objSheet = $newExcel->getActiveSheet(); //获取当前操作sheet的对象
  8. $objSheet->setTitle('导出模板'); //设置当前sheet的标题
  9. // 设置宽度为true,不然太窄了
  10. $newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
  11. $newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
  12. $newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
  13. $newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
  14. $newExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
  15. $newExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
  16. // 设置第一栏的标题
  17. $objSheet->setCellValue('A1','用户id')
  18. ->setCellValue('B1','用户名称')
  19. ->setCellValue('C1','登录密码')
  20. ->setCellValue('D1','头像')
  21. ->setCellValue('E1','真实名称')
  22. ->setCellValue('F1','状态');
  23. //默认数据
  24. $explame_data_list = array(
  25. array(
  26. 'id' => '1',
  27. 'username' => '小明',
  28. 'password' => '15012345678',
  29. 'avatar' => '/upload/img/20220321/asdkjfkasdjf.png',
  30. 'real_name' => '陈亚明',
  31. 'status' => '0',
  32. ),
  33. );
  34. $explame_data_list = Db::connect('mysql2')->table('user')->select();
  35. $baseRow = 2; //数据从N-1行开始往下输出 这里是避免头信息被覆盖
  36. foreach ($explame_data_list as $k => $val) {
  37. $i = $k + $baseRow;
  38. $objSheet->setCellValue('A' . $i, $val['id'])
  39. ->setCellValue('B' . $i, $val['username'])
  40. ->setCellValue('C' . $i, $val['password'])
  41. ->setCellValue('D' . $i, $val['avatar'])
  42. ->setCellValue('E' . $i, $val['real_name'])
  43. ->setCellValue('F' . $i, $val['status']);
  44. }
  45. $result = $this->downloadExcel($newExcel, '会员批量导出', 'Xls');
  46. return $result;
  47. }
  48. // 公共文件,用来传入xls并下载
  49. public function downloadExcel($newExcel, $filename, $format){
  50. // $format只能为 Xlsx 或 Xls
  51. // if ($format == 'Xlsx') {
  52. // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  53. // } elseif ($format == 'Xls') {
  54. // header('Content-Type: application/vnd.ms-excel');
  55. // }
  56. // header("Content-Disposition: attachment;filename=". $filename . date('Y-m-d') . '.' . strtolower($format));
  57. // header('Cache-Control: max-age=0');
  58. // $objWriter = IOFactory::createWriter($newExcel, $format);
  59. // $objWriter->save('php://output');
  60. // 通过php保存到本地的时候需要用到
  61. $filenames = root_path() . '/public/storage/office/' . $filename . date('Y-m-d') . '.' . $format;
  62. $writer = IOFactory::createWriter($newExcel, $format);
  63. $writer->save($filenames);
  64. $data = ['file_url' => 'office/' . $filename . date('Y-m-d') . '.' . $format];
  65. return Result::Success($data,'导出成功!');
  66. // exit;
  67. }
  • 如果直接导出可以用 $objWriter->save(‘php://output’),一般前后端分离就要先保存到本地,然后提供本地的导出文件链接给前端,供前端下载。

三、导出word

  • 安装PhpWord扩展包
  1. composer require phpoffice/phpword
  • 用到的地方引入扩展包
  1. use \PhpOffice\PhpWord\TemplateProcessor;
  • 提前制作好 Word 模板,进行内容替换,以达到生成新Word文档的目的

  • 具体代码

  1. /**
  2. * 导出word
  3. */
  4. public function exportWord(){
  5. $tp = new TemplateProcessor(root_path() . '/public/storage/office/word导出模板.docx');
  6. $tp->setValue('company_name','食安科技股份公司');
  7. $tp->setValue('legal_person','张三');
  8. $tp->setValue('appId','sdfkasdf4845485a4');
  9. $tp->setValue('address','深圳市龙华区观澜街道');
  10. $tp->setValue('code_num','121223324asdfas');
  11. $tp->setValue('contact_name','李四');
  12. $tp->setValue('contact_phone','1578178547');
  13. // $tp->setImageValue('license_img',root_path() . '/public/storage/office/license.png');
  14. $tp->setImageValue('license_img',['path'=>root_path() . '/public/storage/office/license.png','width'=>250,'height'=>200]);
  15. $filename = root_path() . '/public/storage/office/小程序主体信息导出.docx';
  16. $tp->saveAs($filename);
  17. // $name = pathinfo($filename,PATHINFO_FILENAME);
  18. // return download($filename,$name)->expire(0);
  19. $data = ['file_url' => 'office/小程序主体信息导出.docx'];
  20. return Result::Success($data,'导出成功!');
  21. }
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post