Php excel в массиве

Is it possible to import each line of an XLSX file to a row in a PHP array?

Sinister Beard's user avatar

asked Nov 18, 2012 at 10:45

ddfgdfdfgdfgdfgfdgfdgdg's user avatar

2

You can use PHPExcel which is available here: https://phpexcel.codeplex.com/releases/view/119187

Here is what I use to read either xls or xlsx to an array:

require_once('/path/to/PHPExcel.php');

$filename = "example.xlsx";
$type = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($type);
$objPHPExcel = $objReader->load($filename);

foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
    $worksheets[$worksheet->getTitle()] = $worksheet->toArray();
}

print_r($worksheets);

UPDATE / 2022-02-13:

PhpSpreadsheet has been available for a few years now and has replaced PHPExcel. The following code is more or less the same as above with a couple small improvements:

  1. Converted code to a function or method.
  2. Auto detect filetype.
  3. Added ability to specify how null values, formatting and formulas are handled.
  4. Most importantly, call the destructor and clear memory. Without this last step I was running out of memory all the time after loading large files.
/**
 * Create a multidimensional array of worksheets from a filename.
 *
 * @param mixed $nullValue Value returned in the array entry if a cell doesn't exist
 * @param bool $calculateFormulas Should formulas be calculated?
 * @param bool $formatData Should formatting be applied to cell values?
 *
 * @return array
 */
function spreadsheet_to_array($nullValue = null, $calculateFormulas = true, $formatData = false) {
    $results = [];
    $spreadsheet = PhpOfficePhpSpreadsheetIOFactory::load($file);
    foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
        $results[$worksheet->getTitle()] = $worksheet->toArray($nullValue, $calculateFormulas, $formatData);
    }
    // save memory
    $spreadsheet->__destruct();
    $spreadsheet = NULL;
    unset($spreadsheet);
    return $results;
}

answered May 1, 2015 at 21:01

Eaten by a Grue's user avatar

Eaten by a GrueEaten by a Grue

20.8k10 gold badges81 silver badges104 bronze badges

3

I use this:

include 'simplexlsx.class.php';
$xlsx = @(new SimpleXLSX('myFile.xlsx'));
$data =  $xlsx->rows();

You can simplexslx from here.

UPDATE

Apparently the link above doesn’t work anymore. You can now use this. (Thanks @Basti)

answered Jul 6, 2015 at 0:39

rockstardev's user avatar

rockstardevrockstardev

13.6k39 gold badges163 silver badges294 bronze badges

2

Problem can be solved using PHPExcel library:

$data = [];

$type = PHPExcel_IOFactory::identify($filepath);
$objReader = PHPExcel_IOFactory::createReader($type);

$objPHPExcel = $objReader->load($filepath);

$rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
foreach($rowIterator as $row){
    $cellIterator = $row->getCellIterator();
    foreach ($cellIterator as $cell) {
        $data[$row->getRowIndex()][$cell->getColumn()] = $cell->getCalculatedValue();
    }
}

where $filepath — path to your xls or xlsx file.

answered Sep 25, 2017 at 14:08

ns16's user avatar

Yes with phpspreadsheet :

  include 'vendor/autoload.php';
        if($_FILES["import_excel"]["name"] != '')
        {
            $allowed_extension = array('xls', 'csv', 'xlsx');
            $file_array = explode(".", $_FILES["import_excel"]["name"]);
            $file_extension = end($file_array);
            if(in_array($file_extension, $allowed_extension))
            {
                $file_name = time() . '.' . $file_extension;
                move_uploaded_file($_FILES['import_excel']['tmp_name'], $file_name);
                $file_type = PhpOfficePhpSpreadsheetIOFactory::identify($file_name);
                $reader = PhpOfficePhpSpreadsheetIOFactory::createReader($file_type);
                $spreadsheet = $reader->load($file_name);
                unlink($file_name);
                $data = $spreadsheet->getActiveSheet()->toArray();
                foreach($data as $row)
                {
                    $insert_data = array(
                        ':test1'          =>  $row[0],
                        ':test2'          =>  $row[1],
                        ':test3'          =>  $row[2],
                        ':test4'          =>  $row[3]
                    );
                 };
                $query = "
                    INSERT INTO post
                    (  test1, test2, test3, test4)
                    VALUES
                    ( :test1, :test2, :test3, :test4)
                ";
                $statement = $connect->prepare($query);
                $statement->execute($insert_data);
             }
             echo "succes";
        }else{
           echo "only xls,csv,xlsx are allowed";
        }

answered Oct 13, 2020 at 14:05

Wassim Redaouia's user avatar

<?php
require_once 'SimpleXLSX.php';

if ( $xlsx = SimpleXLSX::parse('pricelist.xlsx') ) {
  print_r( $xlsx->rows() );
} else {
  echo SimpleXLSX::parseError();
}
?>

SimpleXLSX

answered Aug 20, 2021 at 15:38

Sergey Shuchkin's user avatar

Главная

Инструменты

Excel в PHP-массив онлайн

14.12.2017

24125

1 комментарий

В закладки

20

5

Загрузите файл Excel чтобы перевести его в массив PHP, JS, JSON.

Перетащите сюда файл xls, xlsx, csv
или
выберите файл

Номер листа в excel Удалить пустые строки
Начать со строки Удалить пустые колонки
Кодировка файла Добавить ключи в массив

PHP массив

JS массив

JSON

SQL

14.12.2017, обновлено 05.12.2022

24125

В закладки

20

5

Комментарии 1

Farrux Xalmuratov
Farrux Xalmuratov

15 января 2022 в 19:16

+2

Wy not working convertor?

Ответить

  • Скопировать ссылку
  • Пожаловаться

Авторизуйтесь, чтобы добавить комментарий.

Clients often prefer to send me Excel .xlsx files that are basically just CSV files. E.g. there is just one sheet and it’s simply a table of data starting from A0.
In such circumstances, one can manually convert them to CSV format,
or one can have PhpSpreadsheet read them directly as-is.
This tutorial will show you how to do the latter.

Steps

Below is an commented example of how to read a .xlsx spreadsheet that does better to explain than I could do with words.

<?php

// include the autoloader, so we can use PhpSpreadsheet
require_once(__DIR__ . '/vendor/autoload.php');

# Create a new Xls Reader
$reader = new PhpOfficePhpSpreadsheetReaderXlsx();

// Tell the reader to only read the data. Ignore formatting etc.
$reader->setReadDataOnly(true);

// Read the spreadsheet file.
$spreadsheet = $reader->load(__DIR__ . '/path/to/file.xlsx');

$sheet = $spreadsheet->getSheet($spreadsheet->getFirstSheetIndex());
$data = $sheet->toArray();

// output the data to the console, so you can see what there is.
die(print_r($data, true)); 

With the following example file, you get the following output:

Array
(
    [0] => Array
        (
            [0] => ID
            [1] => Circumstance
        )

    [1] => Array
        (
            [0] => 1
            [1] => Metal-Detecting
        )

    [2] => Array
        (
            [0] => 2
            [1] => Chance find
        )

    [3] => Array
        (
            [0] => 3
            [1] => Fieldwalking
        )

    [4] => Array
        (
            [0] => 4
            [1] => Mudlarking
        )

    [5] => Array
        (
            [0] => 5
            [1] => Gardening
        )

    [6] => Array
        (
            [0] => 6
            [1] => Other chance find
        )

    [7] => Array
        (
            [0] => 7
            [1] => Archaeological investigation
        )

    [8] => Array
        (
            [0] => 8
            [1] => Construction
        )

    [9] => Array
        (
            [0] => 9
            [1] => Agriculture or drainage work
        )

    [10] => Array
        (
            [0] => 10
            [1] => Investigation of shipwreck
        )

    [11] => Array
        (
            [0] => 11
            [1] => Unknown
        )

)

However, I found that if I opened the spreadsheet (in LibreOffice), and pressed Ctrl + A to select all cells, and then manually set the font to Arial, I generated the following
bad example
that would consider every cell to having an empty value. This suggests to me that the $reader->setReadDataOnly(true); doesn’t quite cover me. If you know of a change that will
resolve this, then please paste a solution in the comments.

Last updated: 23rd February 2022
First published: 23rd February 2022

В профессии разработчика часто приходится сталкиваться с работой с табличными данными (списки товаров, новостей, мероприятий). С точки зрения пользователя проще всего работать с excel или google sheets api и заказчик зачастую может прислать данные для импорта на сайт в одном из этих форматов. Сегодня мы рассмотрим простую библиотеку SimpleXLSX, которая умеет конвертировать excel-файл в формате .xlsx в обычный массив на php.

Скачать библиотеку вы можете по ссылке с github. Я работаю в основном с WordPress, поэтому ее подключение у меня выглядит следующим образом:

require_once get_template_directory() . '/includes/plugin-additions/simplexlsx.class.php';

В качестве примера мы будем использовать простой пример списка городов:

Обработка такого массива может выглядеть следующим образом: первую строку мы собираем в массив заголовков, остальные строки соотносим с этими заголовками, если файла не существует, то возвращаем ошибку.

// Simple XLSX Parser Template
$fileImport = get_stylesheet_directory() . '/data/example.xlsx';
if ( $xlsx = SimpleXLSX::parse( $fileImport )) {
	$sheetData = $xlsx->rows(1);

	$excel = array();
	$names = array();
	foreach ( $sheetData as $keyD => $sheetRow ) {
		if ( $keyD == 0 ) {
			foreach	( $sheetRow as $keyC => $sheetCol ) {
				if ( $sheetCol ) $names[$keyC] = $sheetCol;
			}
		} else {

			if ( $sheetRow['0'] ) $title = $sheetRow['0'];

			foreach	( $sheetRow as $keyC => $sheetCol ) {
				if ( isset( $title ) && $sheetCol ) {
					$excel[$title][$names[$keyC]] = $sheetCol;
				}
			}

			unset( $title );

		} // // end if $keyD != 0
	} // end foreach $sheetData
	var_dump( $excel );

} else {
	var_dump( SimpleXLSX::parse_error() );
}

Итоговый массив $excel в этом примере выглядит так:

array(5) {
  ["Архангельск"]=>
  array(4) {
    ["title"]=>
    string(22) "Архангельск"
    ["english"]=>
    string(11) "Arkhangelsk"
    ["ISO"]=>
    string(6) "RU-ARK"
    ["population"]=>
    string(7) "346 979"
  }
  ["Волгоград"]=>
  array(4) {
    ["title"]=>
    string(18) "Волгоград"
    ["english"]=>
    string(9) "Volgograd"
    ["ISO"]=>
    string(6) "RU-VGG"
    ["population"]=>
    string(9) "1 008 998"
  }
  ["Кемерово"]=>
  array(4) {
    ["title"]=>
    string(16) "Кемерово"
    ["english"]=>
    string(8) "Kemerovo"
    ["ISO"]=>
    string(6) "RU-KEM"
    ["population"]=>
    string(7) "556 382"
  }
  ["Тамбов"]=>
  array(4) {
    ["title"]=>
    string(12) "Тамбов"
    ["english"]=>
    string(6) "Tambov"
    ["ISO"]=>
    string(6) "RU-TAM"
    ["population"]=>
    string(7) "292 140"
  }
  ["Хабаровск"]=>
  array(5) {
    ["title"]=>
    string(18) "Хабаровск"
    ["english"]=>
    string(10) "Khabarovsk"
    ["ISO"]=>
    string(24) "RU-KHA"
    ["population"]=>
    string(24) "616 372"
  }
}

PS. Эта библиотека не умеет писать в excel-файлы и в случае такой необходимости есть отдельная библиотека simplexlsxgen того же автора.

Читайте также

@calvinchoy

Created

June 20, 2013 08:46

Star

PHP — excel to array helper function


This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters

Show hidden characters

<?php
/*
|—————————————————————————
| Excel To Array
|—————————————————————————
| Helper function to convert excel sheet to key value array
| Input: path to excel file, set wether excel first row are headers
| Dependencies: PHPExcel.php include needed
*/
function excelToArray($filePath, $header=true){
//Create excel reader after determining the file type
$inputFileName = $filePath;
/** Identify the type of $inputFileName **/
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
/** Create a new Reader of the type that has been identified **/
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
/** Set read type to read cell data onl **/
$objReader->setReadDataOnly(true);
/** Load $inputFileName to a PHPExcel Object **/
$objPHPExcel = $objReader->load($inputFileName);
//Get worksheet and built array with first row as header
$objWorksheet = $objPHPExcel->getActiveSheet();
//excel with first row header, use header as key
if($header){
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$headingsArray = $objWorksheet->rangeToArray(‘A1:’.$highestColumn.‘1’,null, true, true, true);
$headingsArray = $headingsArray[1];
$r = —1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray(‘A’.$row.‘:’.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row][‘A’])) && ($dataRow[$row][‘A’] > »)) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading) {
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
}
else{
//excel sheet with no header
$namedDataArray = $objWorksheet->toArray(null,true,true,true);
}
return $namedDataArray;
}
?>

Понравилась статья? Поделить с друзьями:
  • Php excel без библиотек
  • Php excel with csv
  • Php excel to pdf converter
  • Php excel spreadsheet excel writer
  • Php excel spreadsheet excel reader