Conversor de arquivo Excel para um Array
Publicado por Anderson Irias Hermogenes (última atualização em 06/03/2019)
[ Hits: 7.043 ]
Homepage: https://irias.com.br
Este é um simples script em PHP que converte um arquivo Microsoft Excel (.xlsx) em um Array PHP, em que cada célula do arquivo Excel se transforma em um índice do Array. Para seu funcionamento ele depende da classe ZipArchive. Link oficial: http://php.net/manual/en/class.ziparchive.php.
Um arquivo Microsoft Excel (.xlsx), está no formato .zip.
Comando file utilizado no terminal do Linux Ubuntu para visualizar o real formato do arquivo:
$ file teste-tabela-excel.xlsx
teste-tabela-excel.xlsx: Zip archive data, at least v2.0 to extract
Assim para realizar sua leitura, é necessário descompactar o arquivo .xlsx e pegar os dados necessários para o converter em um Array PHP. Em meu Git Hub disponibilizei o script e um arquivo para teste. Link: https://github.com/andersonirias/xlsx-array-conversor.
<?php $zip = new ZipArchive; $res = $zip->open('teste-tabela-excel.xlsx'); if ($res === true) { $zip->extractTo('xlsx/'); $zip->close(); $sheet1 = simplexml_load_file('xlsx/xl/worksheets/sheet1.xml'); if ($sheet1 == false) exit('Falha ao abrir o arquivo sheet1.xml'); $tabela = []; foreach ($sheet1 as $item['row']) { foreach ($item['row'] as $item2['row']) { if (count($item2['row']) > 0) { foreach ($item2['row']->c as $row) { $atr = json_decode(json_encode($row), 1); if ($atr == false) exit('Falha ao converter dados'); if (isset($atr['@attributes']['t'])) $tabela[$atr['@attributes']['r']] = true; else $tabela[$atr['@attributes']['r']] = 'vazio'; } } } } if (count($tabela) > 0) { $sharedStrings = simplexml_load_file('xlsx/xl/sharedStrings.xml'); if ($sharedStrings == false) exit('Falha ao abrir o arquivo sharedStrings.xml'); $i = 0; $dados = json_decode(json_encode($sharedStrings), 1); if ($dados == false) exit('Falha ao converter dados do arquivo sharedStrings.xml'); foreach ($tabela as $key => $item) { if (trim($item) != 'vazio') { $tabela[$key] = $dados['si'][$i]['t']; $i++; } } } } else { exit('Falha ao abrir arquivo .xlsx'); } print_r($tabela); ?>
Visualizador de Imagens em PHP-GTK2
Função para formatar tamanho de arquivo
Redimensionamento de imagem JPEG
Apresentar imagens - Aleatorio na Pagina (todos os Formatos)
Abrindo arquivo e convertendo de um caracter para outro
Nenhum comentário foi encontrado.
Como gerar um podcast a partir de um livro em PDF
Automatizando digitação de códigos 2FA no browser
Resolver problemas de Internet
Como compartilhar a tela do Ubuntu com uma Smart TV (LG, Samsung, etc.)
Como Instalar o Microsoft Teams no Linux Ubuntu
Músicas de Andrew Hulshult no DOOM (WAD)
Instalar o Apache, MySQL e PHP no Oracle Linux 8
Bloqueando telemetria no Deepin 23.1
Como converter imagens PNG/JPEG para SVG em linha de comando