Lançado Adianti Framework 8.1!
Clique aqui para saber mais
Utilizar PhpSpreadsheet Alguém já utilizou via composer a biblioteca PhpSpreadsheet?. Fiz a instalação, mas quando vou utilizar da mensagem de erro informando que não localizou a classe. Código simples: ...
HT
Utilizar PhpSpreadsheet  
Alguém já utilizou via composer a biblioteca PhpSpreadsheet?. Fiz a instalação, mas quando vou utilizar da mensagem de erro informando que não localizou a classe.

Código simples:
  1. <?php
  2. class teste{
  3. $spreadsheet = new Spreadsheet();
  4. $sheet $spreadsheet->getActiveSheet();
  5. $sheet->setCellValue('A1''Hello World !');
  6. $writer = new Xlsx($spreadsheet);
  7. $writer->save('hello world.xlsx');    
  8. }
  9. ?>


Erro:
PHP Parse error: syntax error, unexpected '$spreadsheet' (T_VARIABLE), expecting function (T_FUNCTION) in /var/www/html/sgi/app/control/sistema/dev-teste/teste.class.php on line 5

Curso Dominando o Adianti Framework

O material mais completo de treinamento do Framework.
Curso em vídeo aulas + Livro completo + Códigos fontes do projeto ERPHouse.
Conteúdo Atualizado!


Dominando o Adianti Framework Quero me inscrever agora!

Comentários (11)


MG

ac
NR

O erro não diz que a classe não foi encontrada, diz que há um erro de sintaxe.
"PHP Parse error: syntax error"

Quando trabalhar com classes o código deve obrigatoriamente estar dentro de uma função:
"unexpected '$spreadsheet' (T_VARIABLE), expecting function (T_FUNCTION)", ou seja, em $spreadsheet o php espera encontrar uma função mas encontrou uma variável
HT

Realmente, nas pressas nem consegui raciocinar, mais quando li o erro e reformulei, passou direitinho. Outro problema que estava fazendo era colocar o "use" dentro da classe e não antes.

Vlw pelo retorno.
HT

  1. <?php
  2. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  3. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  4. class teste extends TPage{
  5.     function __construct(){
  6.         parent::__construct();
  7.     }
  8. function teste(){
  9. $spreadsheet = new Spreadsheet();
  10. $sheet $spreadsheet->getActiveSheet();
  11. $sheet->setCellValue('A1''Hello World !');
  12. $writer = new Xlsx($spreadsheet);
  13. $writer->save('hello world.xlsx');
  14. }    
  15. }
  16. ?>
AF

Boa noite a todos.
Muito boa a dica de vocês.
Precisei utilizar a biblioteca e junto com o artigo, "Integrar bibliotecas pelo composer no Adianti Framework 5", do Pablo consegui fazê-la funcionar.
Parabéns a todos.
Att,
Ailton Furtado
MG

Consegui implementar e estou gerando as planilhas.
O problema que estou enfrentando e enviá-la para o navegador via download.
Usando o TPage::openFile(). ele abre as opções do navegador: abrir ou download.
Se tentar abrir dá erro, pois ele diz que o arquivo não existe, mas se fizer o download, na pásta, ele abre normalmente.
Alguém já conseguiu finalizar a implementação e permitir que o usuário abra com o aplicativo padrão, ao invés de apenas baixá-lo?
HT

Já consigo utilizar... posta a parte do teu código para dar uma olhada.
MG

Segue

Instalação
composer require phpoffice/phpspreadsheet

  1. <?php
  2. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  3.     public function onExcel($param)
  4.     {
  5.         try {
  6.             TTransaction::open('app');
  7.             
  8.             $arquivo 'app/output/plano_contas.xls';    
  9.             $plan = new Spreadsheet();
  10.             $sheet $plan->getActiveSheet();
  11.             
  12.             // cabecalho
  13.             $sheet->setCellValue('A1','ID');
  14.             $sheet->setCellValue('B!','COGIGO');
  15.             $sheet->setCellValue('C1','DESCRICAO');
  16.             
  17.             // dados    public function onExcel($param)
  18.     {
  19.         try {
  20.             TTransaction::open('app');
  21.             
  22.             $arquivo 'app/output/plano_contas.xls';    
  23.             $plan = new Spreadsheet();
  24.             $sheet $plan->getActiveSheet();
  25.             
  26.             // cabecalho
  27.             $sheet->setCellValue('A1','ID');
  28.             $sheet->setCellValue('B!','COGIGO');
  29.             $sheet->setCellValue('C1','DESCRICAO');
  30.             
  31.             // dados
  32.             $planos PlanoConta::where('id','>',0)->load();
  33.             $i 2;
  34.             foreach($planos as $plano) {
  35.                 $sheet->setCellValue("A{$i}",$plano->id);
  36.                 $sheet->setCellValue("B{$i}",$plano->codigo);
  37.                 $sheet->setCellValue("C{$i}",$plano->descricao);
  38.                 $i++;
  39.             }
  40.              
  41.             TTransaction::close();
  42.             // grava o arquivo
  43.             $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($plan'Xls');
  44.             $writer->save($arquivo);
  45.             
  46.             TPage::openFile($arquivo);
  47.             new TMessage('info','Arquivo Gerado com Sucesso',
  48.                          new TAction([$this'onReload']));    
  49.             
  50.         } catch (Exception $e) {
  51.             new TMessage('error'$e->getMessage());
  52.         }
  53.     }
  54.             $planos PlanoConta::where('id','>',0)->load();
  55.             $i 2;
  56.             foreach($planos as $plano) {
  57.                 $sheet->setCellValue("A{$i}",$plano->id);
  58.                 $sheet->setCellValue("B{$i}",$plano->codigo);
  59.                 $sheet->setCellValue("C{$i}",$plano->descricao);
  60.                 $i++;
  61.             }
  62.              
  63.             TTransaction::close();
  64.             // grava o arquivo
  65.             $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($plan'Xls');
  66.             $writer->save($arquivo);
  67.             
  68.             TPage::openFile($arquivo);
  69.             new TMessage('info','Arquivo Gerado com Sucesso',
  70.                          new TAction([$this'onReload']));    
  71.             
  72.         } catch (Exception $e) {
  73.             new TMessage('error'$e->getMessage());
  74.         }
  75.     }
  76. ?>
HT

Tenta usar esse código para gerar:

  1. <?php
  2. $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  3. $writer->save('tmp/'.$file.'.xlsx');
  4. TPage::openFile('tmp/'.NOME DO ARQUIVO.'.xlsx');
  5. ?>


Não entendi porque de tantos:
$plan = new Spreadsheet();
$sheet = $plan->getActiveSheet();

Se não diferencia as abas que são geradas no excell.

Fonte da biblioteca: https://phpspreadsheet.readthedocs.io/en/develop/
HT

Fiz algo rápido que dá para ajudar..

  1. <?php
  2. $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
  3. $sheet $spreadsheet->getActiveSheet();
  4. $sheet->setCellValue('A1''EMPRESA TESTE  LTDA');
  5. $sheet->setCellValue('A2''Emissão: ' date('d/m/Y'));
  6. $sheet->setCellValue('A3''Relatorio de estoque');
  7. $sheet->setCellValue('A5''Descrição');
  8. $sheet->setCellValue('B5''Estoque');
  9. $sheet->setCellValue('C5''Transito');
  10. $sheet->setCellValue('D5''Lote');
  11. $spreadsheet->getActiveSheet()->getStyle('A1:A3')->getFont()->setBold(true);
  12. $spreadsheet->getActiveSheet()->getStyle('A1:A3')->getFill()
  13.                 ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  14.                 ->getStartColor()->setARGB('87CEFA');
  15. $linha 6;
  16. foreach($dados as $dado)
  17. {
  18. $sheet->setCellValue('A' $linhautf8_encode($dado["Descricao"]));
  19. $sheet->setCellValue('B' $linha$dado["Qtd_Disponivel"]);
  20. $sheet->setCellValue('C' $linha$dado["Qtd_Transito"]);
  21. $sheet->setCellValue('D' $linha$dado["Cod_Lote"]);
  22. $linha++;
  23. }
  24. $nome_arq 'Relatorio Estoque ' date('-dmY-His') . '.xlsx';
  25. $spreadsheet->getActiveSheet()->setTitle('Relatorio Gerencial de vendas');
  26. $writer = new PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
  27. $writer->save('tmp/'.$nome_arq);
  28. TPage::openfile('tmp/'$nome_arq);
  29. ?>



MG

Oi Herbety foi um reaproveitamento.
Acredito que seja de versões anteriores.
Vou implementar da forma sugerida.
Muito obrigado.