humanemulator.net — справка. Продукт, демо и покупка — на хуманэмулятор.рф | Демо | Купить | API | Changelog

get_sheet_by_page

get_sheet_by_page($path,$sheet,$skip=0,$limit=10,$timeout=3000); - Получить содержимое заданного Листа Excel файла как двумерный массив постранично

Функция на вход принимает параметры:

  • $path – Путь к файлу Excel
  • $sheet – номер Листа
  • $skip – пропустить количество строк
  • $limit – максимальное количество результатов строк
  • $timeout – Таймаут ожидания выполнения операции, сек

    После выполнения функции возвращаемое значение будет равно одному из двух :
  • результат – двухмерный массив значений из прямоугольного диапазона ячеек листа, который начинается с ячейки А1 и заканчивается крайней правой нижней непустой ячейкой.
  • пусто / null – ошибка

    Пример использования
    <?php
    
    // Scenario: Get sheet by page number in Excel file
    
    $xhe_host = getenv("RPABOT_HOST_URL");
    
    // Connect functional objects if not already connected
    if (!isset($path)){
        // Path to the init.php file for connecting to the XHE API
        $path = "../../../Templates/init.php";
        // Including init.php grants access to all classes and functionality for working with the XHE API
        require($path);
    }
    
    echo "\n<span >excelfile->" . basename(__FILE__) . "</span>\n";
    
    // Initialize Excel
    SYSTEM::$excel->kill();
    
    // Example 1: Read sheet content page by page
    echo("Example 1: Get sheet 0 content as array. Paginated traversal\n");
    
    // Extract method arguments into variables
    $filePath = __DIR__ . "/test/test.xlsx";
    $sheetIndex = 0;
    
    // Number of rows to skip
    $skip = 0;
    // Number of rows per page
    $limit = 2;
    
    // Open file
    echo "Open file: ";
    echo SYSTEM::$excelfile->open($filePath) . PHP_EOL;
    
    // Determine number of pages
    $rowsCount = SYSTEM::$excelfile->get_rows_count($filePath, $sheetIndex);
    if ($rowsCount % $limit == 0)
        $pagesCount = $rowsCount/$limit;
    else
        $pagesCount = (int)($rowsCount/$limit) + 1;
    echo "Variables for operation: " . PHP_EOL;
    echo "[Rows count][Rows to skip][Rows per page][Pages count]:  [$rowsCount][$skip][$limit][$pagesCount]" . PHP_EOL;
    
    echo 'Reading page by page: ' . PHP_EOL;
    for($page = 1; $page <= $pagesCount; $page++){
        echo 'Page #[' . $page . '] ' ;
        if ($page == 1){
            $currentRows = SYSTEM::$excelfile->get_sheet_by_page($filePath, $sheetIndex, $skip,  $limit);
        }
        else {
            $skip = ($page  - 1) * $limit;
            $currentRows = SYSTEM::$excelfile->get_sheet_by_page($filePath, $sheetIndex, $skip,  $limit);
        }
    
        if (!$currentRows)
            break;
    
        echo 'Rows count on page: ' .  count($currentRows) . PHP_EOL;
    
        echo 'Rows: '  . PHP_EOL;
        $logStr = '';
        foreach($currentRows as $row){
            $valCount = count($row);
            $logStr = '';
            for ($k = 0; $k < $valCount; $k++){
                if (empty($row[$k]))
                    $logStr = $logStr . ', ' . "''";
                else
                    $logStr = $logStr . ', ' . $row[$k];
            }
            // Remove comma at the beginning
            $logStr = trim($logStr, ',');
            echo '[' . $logStr . ']' . PHP_EOL;
        }
    }
    
    echo 'Close file: ';
    SYSTEM::$excelfile->close($filePath);
    
    // View the result
    
    
    // End of script
    echo "\n";
    
    // Quit
    WINDOW::$app->quit();
    ?>
    # Additional paths
    import sys
    sys.path.insert(0, '../../../Templates PY/')
    
    xhe_host = "127.0.0.1:7010"
    from xweb_human_emulator import *
    
    # начало
    echo("<hr><font color=blue>excelfile.get_sheet_by_page</font><hr>")
    
    # 1 
    echo("\n1. Прочитаем Лист как массив постранично (2 первых строки): \n")
    twoDArray = excelfile.get_sheet_by_page("test\\test.xlsx", 0, 0, 2)
    
    for k in twoDArray:
        for j in k:
            print(j, end = " ")
        print()
    
    # конец
    echo("<hr><br>")
    
    # Quit
    app.quit()
    #region using
    
    using System;
    using System.Diagnostics;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Text;
    using System.Threading;
    
    using XHE;
    using XHE.XHE_DOM;
    using XHE.XHE_System;
    using XHE.XHE_Window;
    using XHE.XHE_Web;
    
    #endregion
    
     class Program:XHEScript
     {
    	  static void Main(string[] args)
    	  {
    			// init XHE
    			server = Environment.GetEnvironmentVariable("RPABOT_HOST_URL");
    			InitXHE();
    
    			// начало
    			echo("<hr><font color=blue>excelfile.get_sheet_by_page</font><hr>");
    
    			// 1
    			echo("1. Получить лист как массив: ");
    			echo(excelfile.get_sheet_by_page("test/test.xlsx", 0, 0, 2));
    
    			// конец
    			echo("\n\n");
    
    			app.quit();            
    	  }
    }
    xhe_host="127.0.0.1:7010";
    echo = require("../../../Templates JS/init.js");
    
    // начало
    echo("<hr><font color=blue>excelfile.get_sheet_by_page</font><hr>");
    
    // 1 
    echo("\n1. Прочитаем Лист как массив частично (2 первых строки) ");
    console.log(excelfile.get_sheet_by_page("test\\test.xlsx",0, 0, 2));
    
    // конец
    echo("\n");
    
    // Quit
    app.quit();

    =============================================
    excelfile    Объекты    DOM  System  Vision  Web  Window        
    =============================================
    если что-то непонятно или необходимо узнать или считаете что надо добавить по работе этой функции, пишите в комментарии или на наш форум
    .