PhpSpreadsheet - XLSX -按顺序读取图表

6qqygrtg  于 11个月前  发布在  PHP
关注(0)|答案(1)|浏览(66)

我正在使用PHPOffice/PhpSpreadsheet库来阅读图表。
现在看起来,阅读图表是按照粘贴图表的顺序(如果后面添加的图表在前面的图表之上,这并不重要)。
我想找到正确绘制图表的方法。有没有可能,从上到下建立秩序?所以最上面的图表总是在索引'0'中?
也有方法来读取图表的名称-我的意思是当你选择一个图表时Exel中的字段:
x1c 0d1x的数据

$reader = IOFactory::createReader('Xlsx');
$reader->setIncludeCharts(true);
$reader->setLoadAllSheets();
$spreadsheet = $reader->load('file.xlsx');

$loadedSheetNames = $spreadsheet->getSheetNames()

foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
  $spreadsheet->setActiveSheetIndexByName($loadedSheetName);
  $activeSheet = $spreadsheet->getActiveSheet();
  $chartNames = $activeSheet->getChartNames();
}

字符串

thigvfpy

thigvfpy1#

您可以通过ChartCollection获取有关图表的所有信息。使用$activeSheet-> getTopLeftCell(),您可以在Excel中获取图表的位置,然后对其进行排序。然后使用该名称获取索引。
$realChartSorting包含ExcelSheet中的排序。

foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $spreadsheet->setActiveSheetIndexByName($loadedSheetName);
    $activeSheet = $spreadsheet->getActiveSheet();
    $realChartSorting = $this->getRealChartOrdering($activeSheet);
    foreach ($realChartSorting as $item) {
        $activeSheet->getChartByName($realChartSorting['chartName']);
        $activeSheet->getChartByIndex($realChartSorting['chartIndex']);
    }
}

private function getRealChartOrdering(Worksheet $activeSheet): array {
    $chartData = [];
    $chartNames = $activeSheet->getChartNames();
    $chartCollection = $activeSheet->getChartCollection();
    foreach ($chartCollection as $item) {
        $chartData[] = [
            'name' => $item->getName(),
            'pos' => $item->getTopLeftCell()
        ];
    }

    // Sort by position
    array_multisort(
        array_column($chartData, 'pos'), SORT_ASC,
        $chartData
    );

    $realChartSorting = [];
    foreach ($chartData as $data) {
        $realChartSorting[] = [
            'chartIndex' => array_search($data['name'], $chartNames),
            'chartName' => $data['name']
        ];
    }

    return $realChartSorting;
}

字符串

相关问题