why get undefined offset when importing excel file to the database using laravel.
UserImport.php
public function model(array $row)
{
var_dump($row);
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}
UserImportController
public function store(Request $request){
$file = $request->file('file');
Excel::import(new UsersImport, $file);
return back()->withStatus('Successfully');
}
when uploading the excel file, display it like this.
enter image description here
I used var_dump() to see the array. I entered 4 rows in the excel file. But display 5 array data. Why that??? (display in entered image.
)
I believe it is because of the new line at the end of the file.
You should check if it contains only a new line and skip the import.
set if condition for UserImport.php
if($row[0] !=""){
return new User([
'name' =>$row[0],
'email'=>$row[1],
'password' => Hash::make('password'),
]);
}
Related
I tried to make a function where User could import formatted file such as .csv or .xlsx.
I make the function using Maatwebsite excel library.
When I tried to insert the data to database, a cell that has value of today date 24/01/2023 is converted to 44950
My Import model kinda like this
public function model(array $row)
{
return new Event([
/**
* Other attributes and columns
*
*/
'date' => $row[1],
]);
}
How to convert those value to 'Y-m-d'?
I found the best solutions, idk what happened to the excel imported files, but this helps me.
use PhpOffice\PhpSpreadsheet\Shared\Date;
public function model(array $row)
{
return new Event([
/**
* Other attributes and columns
*
*/
'date' => Date::excelToDateTimeObject($row[1]),
]);
}
Source: https://github.com/SpartnerNL/Laravel-Excel/issues/1978
How to import file excel with format xlsx to Laravel 8?
I want import an excel file, i success for get data from excel. But when i run query for add data, the value is null.
I have code for import excel like this
Controller
Excel::import(new ImportItem($request->id_warrent), $request->upload);
Import
class ImportItem implements ToModel,WithHeadingRow, WithStartRow
{
public function __construct($id_warrent)
{
$this->id_warrent = $id_warrent;
}
public function model(array $row)
{
return new WarrentItemModel([
'id_warrent_item' => Str::random(5),
'warrent_entry_id' => $this->id_warrent,
'warr_item_category' => $row[0],
'warr_item_code' => $row[1],
'warr_item_nup' => $row[2],
'warr_item_name' => $row[3],
'warr_item_type' => $row[4],
'warr_item_qty' => $row[5],
'warr_item_unit' => $row[6]
]);
}
public function startRow(): int
{
return 3;
}
}
I don't know error position, when i tes $row used dd, i can get data from excel, but when i return new warrent item model, $row can't get value.
test used dd
error can't get value from excel
In your sql table you have you have a column 'warr_item_category', which default property is set to be not null, just set the property of that column to null and it will solve your problem, hope that helps
I have a large number of records in an excel sheet which is taking too much time while importing to the 3 tables in database. To overcome this issue, I am trying to import it through batch by creating small excel files with less data so that I run queue jobs of laravel on it. I am trying with the below code but it doesn't work, it throws an error of Array to String conversion and also sub excel files are not creating. I am using excel Maatweb, but I am handling it through controller.
Can someone lead me please.
function importBatchFiles(Request $request)
{
$this->validate($request, [
'file' => 'required|mimes:xls,xlsx,csv'
]);
$file = $request->file('file');
//$fileName='orders_'.$request->get('company_id').'_'.date('Y-m-d').uniqid().'.xlsx';
if ($file->isValid()) {
//$file->move('order_list', $fileName);
$data = Excel::toArray(new OrdersImport, request()->file('file'));
foreach($data as $key => $value)
{
foreach($value as $row)
{
$inputs[] = $row;
}
}
$data1 = array_slice($inputs, 1);
$parts = (array_chunk($data1, 500));
foreach($parts as $index => $part){
$filename = resource_path('pending-files/'.date('Y-m-d').$index.'.'.$request->file->extension());
file_put_contents($filename, $part);
}
return Response::json(['success' => 'Orders Queued for importing.']);
}else{
return Response::json(['error' => 'Some errror']);
}
}
When using the WithChunkReading concern, you can execute each chunk into a queue job. You can do so by simply adding the ShouldQueue contract.
For more details please refer to this link: https://docs.laravel-excel.com/3.1/imports/queued.html
I'm using laravel. I tried to create an Excel file, and add data into it and download (export) it as Excel file to the client.
But instead of an Excel file being downloaded, it returns a string.
Can someone help me please?
Thanks in advance.
My controller code
use Maatwebsite\Excel\Facades\Excel;
public function exportreport(Request $request){
$file = "users.xlsx";
return Excel::download(new reportExport, $file);
}
my export code
use App\cqqueryformModel;
class reportExport implements FromCollection
{
public function collection(){
return cqqueryformModel::all();
}
}
Return is string instead of the Excel file:
Console log:
console.log
Thanks #Nipun it works.
.done(function (data) {
var url = "{{ url('/cqreportModel/exportreport') }}";
window.open(url, "_blank");
})
I have some code that iterates over the rows and columns of an Excel sheet and replaces text with other text. This is done with a service that has the excel file and a dictionary as parameters like this.
$mappedTemplate = $this->get('app.entity.translate')->translate($phpExcelObject, $dictionary);
The service itself looks like this.
public function translate($template, $dictionary)
{
foreach ($template->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cell) {
if (!is_null($cell)) {
if (!is_null($cell->getCalculatedValue())) {
if (array_key_exists((string)$cell->getCalculatedValue(), $dictionary)) {
$worksheet->setCellValue(
$cell->getCoordinate(),
$dictionary[$cell->getCalculatedValue()]
);
}
}
}
}
}
}
return $template;
}
After some debugging I found out that the text actually is replaced and that the service works like it should. The problem is that when I return the new PHPExcel file as a response to download, the excel is empty.
This is the code I use to return the file.
// create the writer
$writer = $this->get('phpexcel')->createWriter($mappedTemplate, 'Excel5');
// create the response
$response = $this->get('phpexcel')->createStreamedResponse($writer);
// adding headers
$dispositionHeader = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$file_name
);
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response->headers->set('Pragma', 'public');
$response->headers->set('Cache-Control', 'maxage=1');
$response->headers->set('Content-Disposition', $dispositionHeader);
return $response;
What am I missing?
Your code is missing the calls to the writer.
You only create the writer, but never use it, at least not in your shared code examples:
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$response = $this->get('phpexcel')->createStreamedResponse($objWriter)
Another thing is the content type: Do you have the apache content types setup correctly?
$response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8');