Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/wrong-value-of-parsing-dates #4

Merged
merged 2 commits into from
Jun 16, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Date convertion fix for json and collection conversion
  • Loading branch information
rjsamra committed Jun 12, 2024
commit 3dc70cd039db465be74c2ed88c14e49ceb8109af
24 changes: 22 additions & 2 deletions src/ExcelTo.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,41 @@
namespace Knackline\ExcelTo;

use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Shared\Date;

class ExcelTo
{

public static function json($filePath)
{
// Read the Excel data into an array
$excelData = Excel::toArray([], $filePath)[0];

// Extract the header from the data
$header = array_shift($excelData);

// Initialize an empty array to hold the processed data
$jsonData = [];

// Iterate through each row of data
foreach ($excelData as $row) {
$rowData = [];
foreach ($header as $key => $columnName) {
$rowData[$columnName] = $row[$key];
// Check if the column name is "Date" and the value is numeric
if (($columnName === 'date' || $columnName === 'Date') && is_numeric($row[$key])) {
// Convert Excel date to a formatted date string
$rowData[$columnName] = Date::excelToDateTimeObject($row[$key])->format('Y-m-d'); // Format as needed
} else {
$rowData[$columnName] = $row[$key];
}
}
$jsonData[] = $rowData;
}

// Encode the array into JSON format
$json = json_encode($jsonData);

// Decode the JSON back to an array for returning
$decodedJson = json_decode($json, true);

return $decodedJson;
Expand All @@ -37,7 +52,12 @@ public static function collection($filePath)
foreach ($excelData as $row) {
$rowData = [];
foreach ($header as $key => $columnName) {
$rowData[$columnName] = $row[$key];
// Check if the column name is "Date" and the value is numeric
if (($columnName === 'date' || $columnName === 'Date') && is_numeric($row[$key])) {
$rowData[$columnName] = Date::excelToDateTimeObject($row[$key])->format('Y-m-d'); // Format as needed
} else {
$rowData[$columnName] = $row[$key];
}
}
$collection->push($rowData);
}
Expand Down