Yii Framework Forum: Import CSV file with extension yii2-csv-importer - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Import CSV file with extension yii2-csv-importer

#1 User is offline   Gustavo Andrade 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 203
  • Joined: 16-August 11
  • Location:Brazil - MG

Posted 31 December 2017 - 01:49 PM

I'm not sure how to use the extension "yii2-csv-importer".
I need to import a CSV file that is in the app/web/uploads/mod-key.csv directory

My table/model (BASE) and csv file have the following structure:

'id'
'date'
'Pan
'key'
'goal'
'accomplished'
'Weight'
'points'
'update'


How would my ACTION look?

use ruskid\csvimporter\???;
public function actionImpbase()
{

$importer = new CSVImporter();

$importer->setData(new CSVReader([
	'filename' => Yii::$app->request->baseUrl."/uploads/mod-key.csv",
	'tableName' => Base::tableName(),
	'fgetcsvOptions' => [
    	'delimiter' => ';'
	]
]));

	return $this->redirect(['index']);
}

-------------------------------------
https://github.com/gugoan
0

#2 User is offline   alrazi 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,533
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 31 December 2017 - 10:07 PM

the documentation is pretty clear they have very comprehensive examples, you have a creator and a reader you need to run import method with your schema and with callbacks to locate the data column

$importer = new CSVImporter();

$importer->setData(new CSVReader([
        'filename' => Yii::$app->request->baseUrl."/uploads/mod-key.csv",
        'tableName' => Base::tableName(),
        'fgetcsvOptions' => [
        'delimiter' => ';'
        ]
]));

$numberRowsAffected = $importer->import(new MultipleImportStrategy([
    'tableName' => ModelName::tableName(), // change your model names accordingly
    'configs' => [
        [
            'attribute' => 'id',
            'value' => function($line) {
                return $line[0];
            }
        ],
        [
            'attribute' => 'date',
            'value' => function($line) {
                return $line[1];
            }
        ]
// put your remaining columns here
    ],
]));

0

#3 User is offline   Gustavo Andrade 

  • Standard Member
  • PipPip
  • Yii
  • Group: Members
  • Posts: 203
  • Joined: 16-August 11
  • Location:Brazil - MG

Posted 01 January 2018 - 08:25 AM

Worked well, thank you.
-------------------------------------
https://github.com/gugoan
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users