-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge.php
67 lines (55 loc) · 1.84 KB
/
merge.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
/**
* @file
* File to merge all the downloaded files into one file.
*/
require 'vendor/autoload.php';
use Box\Spout\Reader\ReaderFactory;
use Box\Spout\Writer\WriterFactory;
use Box\Spout\Common\Type;
// ... and a writer to create the new file.
$writer = WriterFactory::create(Type::XLSX);
$writer->openToFile('merged_files.xlsx');
$header_processed = FALSE;
// Get all files.
$inputFileNames = array_slice(scandir('dnsfiles'), 2);
// Loop through all the remaining files in the list.
print "Merging all files in merged_files.xlsx.\n\n";
$sheet_count = 1;
foreach ($inputFileNames as $sheet => $inputFileName) {
$file_ext = pathinfo($inputFileName, PATHINFO_EXTENSION);
if ($file_ext === 'xlsx') {
// We need a reader to read the existing file...
$reader = ReaderFactory::create(Type::XLSX);
$reader->open('dnsfiles/' . $inputFileName);
$reader->setShouldFormatDates(TRUE);
// let's read the entire spreadsheet...
foreach ($reader->getSheetIterator() as $sheetIndex => $sheet) {
// Add sheets in the new file, as we read new sheets in the existing one.
if ($sheetIndex !== 1) {
$writer->addNewSheetAndMakeItCurrent();
}
$counter = 0;
foreach ($sheet->getRowIterator() as $row) {
if (($counter == 0) && ($header_processed)) {
$counter++;
continue;
}
if ($counter == 1) {
array_unshift($row, str_replace('.xlsx', '', $inputFileName));
}
else {
array_unshift($row, '');
}
// ... and copy each row into the new spreadsheet.
$writer->addRow($row);
$counter++;
}
}
$reader->close();
print "File -> {$sheet_count}: Merged {$inputFileName}.xlsx file in merged_files.xlsx.\n";
$sheet_count++;
}
}
$writer->close();
print "\nMerged all files in merged_files.xlsx.\n";