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