Conversor de arquivo Excel para um Array

Publicado por Anderson Irias Hermogenes (última atualização em 06/03/2019)

[ Hits: 6.320 ]

Download conversor.php




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.

  



Esconder código-fonte

<?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);
?>

Scripts recomendados

Manipulação de Arquivos XML para OT Server

Download de imagem

Apresentar imagens - Aleatorio na Pagina (todos os Formatos)

Image Class

Gerar código de barras com barcode + PHP


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts