2014-09-23 10 views
7

Sto cercando di esportare alcuni dati dal mio modello in excel scheet con "Laravel Excel", l'ho fatto, ma il mio risultato è molto lontano da quello che mi serve veramente

Questo è ciò che il `VE ha ottenuto in file scaricato: actual laravel excel exportLaravel Excel, esportazione da un modello, problemi di stile

E questo è quello che voglio da compiere: export goal

mio regolatore di parte: parte

//casting export... 
     Excel::create('ExcelExport', function($excel) use($filters, $agents) { 

      $main_arr = array(); 

      foreach($agents as $value){     
       $main_arr[] = Card::cardForUser($value, $filters)->toArray();     
      } 

      $excel->sheet('Sheetshit', function($sheet) use($main_arr) { 
       //You may ask me "why are you using foreach?" 
       // and my answer will be:"I don`t KNOW, because it WORKS!" 

       foreach($main_arr as $one){ 
        $sheet->fromArray($one); 
       } 

      }); 

     })->export('xls'); 

Modello:

public static function cardForUser($user_id, $filters = array()){ 
     $query = static::UserId($user_id);//just gets 'where user id' 

     foreach($filters['fields'] as $select){ 
      $query->addSelect($select); 
     } 
      return $query->get(); 
    }  

    public function scopeUserId($query, $user_id) { 
     return $query->where('user_id', '=', $user_id); 

    } 

$filters gamma sono costituiti da campi nomi DB, quindi decide in sostanza, che le colonne includono in esportazione. Ciò significa che il mio $main_arr possono avere lunghezza dei campi interni da 1 a 5. Ogni agente può avere un sacco di righe in DB o del tutto assenti

Esempio di $ main_arr discarica con 4 filtri set:

array (size=8) 
    0 => 
    array (size=10) 

//thats will be first agent 
      0 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chrysler' (length=8) 
       'ts_model' => string 'PT CRUISER' (length=10) 
      1 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Opel' (length=4) 
       'ts_model' => string 'Corsa' (length=5) 
      2 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Dodge' (length=5) 
       'ts_model' => string 'Stratus' (length=7) 
      3 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Р’РђР—' (length=6) 
       'ts_model' => string '2112' (length=4) 
      4 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Mercedes-Benz' (length=13) 
       'ts_model' => string 'E 270' (length=5) 
      5 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Р’РђР—' (length=6) 
       'ts_model' => string '21140 LADA SAMARA' (length=17) 
      6 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'LADA' (length=4) 
       'ts_model' => string '213100 LADA 4С…4' (length=16) 
      7 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Р’РђР—' (length=6) 
       'ts_model' => string '21110' (length=5) 
      8 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Lanos' (length=5) 
      9 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'VOLKSWAGEN' (length=10) 
       'ts_model' => string 'PASSAT' (length=6) 
//thats will be second agent 
     1 => 
     array (size=10) 
      0 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Mercedes' (length=8) 
       'ts_model' => string 'Benz' (length=4) 
      1 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Corvette' (length=8) 
      2 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Corvette' (length=8) 
      3 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Corvette' (length=8) 
      4 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Corvette' (length=8) 
      5 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Chevrolet' (length=9) 
       'ts_model' => string 'Corvette' (length=8) 
      6 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Mazeratti' (length=9) 
       'ts_model' => string 'M4' (length=2) 
      7 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Ferrari' (length=7) 
       'ts_model' => string 'F4' (length=2) 
      8 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Mazda' (length=5) 
       'ts_model' => string '5' (length=1) 
      9 => 
      array (size=4) 
       'date_start' => string '06.08.2014 10:00:00' (length=19) 
       'ts_category' => int 2 
       'ts_make' => string 'Test' (length=4) 
       'ts_model' => string 'Test' (length=4) 
     etc... 

Sooo ... le mie domande sono:

  1. Come faccio a impostare il titolo principale ("roba Header" nell'esempio img)?
  2. perché le intestazioni delle colonne (data_start, ts_category, ts_make, ts_model) scompaiono nel primo elemento dell'array? (Si può vedere al primo img che non ho intestazioni "data start" e "ts_category" per il primo sotto-array. A volte BTW non ha intestazioni per il primo sotto-array!)
  3. Latta Rendo le intestazioni del mio sotto-array in grassetto (ts_make, ecc.)? Come?
  4. Come posso creare sottotitoli per ogni agente (ho intenzione di utilizzare il tasto sub-array per visualizzare un numero di agenti)?

UPDATE inviato il codice di lavoro come risposta.

risposta

20

Non risponderò a tutte le vostre domande perché sarà necessario consultare la documentazione per conto proprio.Tuttavia vi mostrerò come ottenere tale effetto: enter image description here

e penso che vi aiuterà più di spiegare che cosa avete sbagliato

Il codice per il file indicato sopra eccellere è qui sotto:

Excel::create('ExcelExport', function ($excel) { 

    $excel->sheet('Sheetname', function ($sheet) { 

     // first row styling and writing content 
     $sheet->mergeCells('A1:W1'); 
     $sheet->row(1, function ($row) { 
      $row->setFontFamily('Comic Sans MS'); 
      $row->setFontSize(30); 
     }); 

     $sheet->row(1, array('Some big header here')); 

     // second row styling and writing content 
     $sheet->row(2, function ($row) { 

      // call cell manipulation methods 
      $row->setFontFamily('Comic Sans MS'); 
      $row->setFontSize(15); 
      $row->setFontWeight('bold'); 

     }); 

     $sheet->row(2, array('Something else here')); 

     // getting data to display - in my case only one record 
     $users = User::get()->toArray(); 

     // setting column names for data - you can of course set it manually 
     $sheet->appendRow(array_keys($users[0])); // column names 

     // getting last row number (the one we already filled and setting it to bold 
     $sheet->row($sheet->getHighestRow(), function ($row) { 
      $row->setFontWeight('bold'); 
     }); 

     // putting users data as next rows 
     foreach ($users as $user) { 
      $sheet->appendRow($user); 
     } 
    }); 

})->export('xls'); 
+3

Questo ha aiutato molto, grazie. Desiderio "Maatwebsite" mettere qualcosa come questo come esempio per la sua guida. – Zanshin13

2

enter image description here

  1. Come impostare il titolo principale ("roba Header" nell'esempio img)?

    Guardate la documentazione, è molto facile:

    $sheet->prependRow(1, array(
        'Example header' 
        ))->cell('A1', function($cell) { 
         $cell->setFontWeight('bold'); 
         $cell->setFontSize(18); 
    }); 
    
  2. Posso fare le intestazioni di mio sub-array grassetto (ts_make, ecc)? Come?

    conte quello righe devono essere in grassetto:

    $count = 2; 
    foreach($main_arr as $one){ 
        $sheet->fromArray($one, null, 'A2'); 
    
        $sheet->row($count, function($row) { 
         $row->setFontWeight('bold'); 
        }); 
        $count += count($one) + 1; 
    } 
    
  3. Come posso fare i sottotitoli per ogni agente (I progettando di utilizzare sub-arraykey per visualizzare una serie di agente)?

    In modo simile a quanto sopra :)

+0

Grazie per l'aiuto, ho usato l'idea di conteggio nel mio codice! Sfortunatamente, la tua risposta non ha potuto risolvere completamente i miei problemi, ma ho votato :) – Zanshin13

+0

Ehi, come posso leggere quel tipo di file Excel usando Laravel-Excel Mattwebsite? –

+0

@RenishKhunt Cosa intendi per "leggere", esattamente? È possibile aprirlo con qualsiasi software simile a Excel (OpenOffice, LibreOffice, ecc.). Se si intende "leggere" utilizzando il codice, è possibile utilizzare la funzione del pacchetto 'Excel :: load ('file.xls', function ($ reader) { // metodi reader });' o qualsiasi altra funzione di file 'php'. Puoi leggere di più qui http://www.maatwebsite.nl/laravel-excel/docs/import – Zanshin13

0

Con l'aiuto di Marcin e r4xz `ve vengono a questo codice di lavoro:

Excel::create('Filename', function($excel) use($filters, $agents) { 

      $excel->sheet('sheetname', function($sheet) use($agents, $filters) { 
       // first row with header title 
       $sheet->mergeCells('A1:E1');//merge for title 
       $sheet->row(1, function ($row) { 
        $row->setFontSize(18); 
       }); 
       $sheet->row(1, array('Header Stuff'));//add title 

       $sub_titles = array(/*content*/);//array for agents names     

       $count = 2;//pointer for rows with agents name 
       foreach($agents as $agent_id){ 
        //get agent name. 
        $agent_name = Model::AgentById(Auth::user(), $agent_id); 

        $sheet->appendRow(array($agent_name));//add agent name 
        $sheet->mergeCells('A'.$count.':'.'E'.$count);//merge for agent name 
        $sheet->row($sheet->getHighestRow(), function ($row) {//get last row at the moment and style it 
         //$row->setFontWeight('bold'); 
         $row->setFontSize(14); 
        }); 

        $cards = CardModel::cardForUser($agent_id, $filters)->toArray();//get cards for agent 
        //if there is cards show them, else show nothing message 
        if(count($cards) > 0){ 
         $sheet->appendRow($sub_titles);//add sub-titles of agents fields 
         $sheet->row($sheet->getHighestRow(), function ($row) { 
          $row->setFontWeight('bold'); 
         }); 
         foreach($cards as $card){//add all agent fields 
          $sheet->appendRow($card); 
         } 
         $count += count($cards) + 2; 
        } 
        else{ 
         $sheet->appendRow(array('nothing to show')));//add nothing to show message 
         $sheet->row($sheet->getHighestRow(), function ($row) { 
          $row->setFontWeight('bold'); 
         }); 
         $count += 2; 
        } 
       } 
      }); 

     })->export('xls'); 
0

vi consiglio di creare un file excel con lo stile desiderato, quindi allegare i dati a questo file modello, segui questo esempio:

public function export_xls($expense_id, $file_format_id){ 

    $expense  = Expense::find($expense_id); 
    $file_format = FileFormat::find($file_format_id); 

    $routes = DB::table('buy_orders') 
     ->join('expenses','expenses.id','=','buy_orders.expense_id') 
     ->join('users','expenses.user_id','=','users.id') 
     ->select(
      'buy_orders.code', 
      'buy_orders.cost_center', 
      'buy_orders.book_account', 
      'buy_orders.active', 
      'buy_orders.expenditure', 
      'buy_orders.inventory', 
      'buy_orders.quantity', 
      'buy_orders.price_unit', 
      'buy_orders.description', 
      'buy_orders.estimated_value', 
      'buy_orders.destination', 
      'buy_orders.delivery_date' 
     ) 
     ->where('buy_orders.expense_id','=',$expense_id) 
     ->orderBy('buy_orders.created_at','desc') 
     ->get(); 

    $data = json_decode(json_encode((array) $routes), true); 

    Excel::load('/storage/app/template.xls', function($file) use($expense, $data){ 

     $file->setActiveSheetIndex(0)->setCellValue('D8', $expense->user->name); 
     $file->setActiveSheetIndex(0)->setCellValue('L8', $expense->application_date); 
     $file->setActiveSheetIndex(0)->setCellValue('P8', $expense->code); 
     $file->setActiveSheetIndex(0)->setCellValue('D45', $expense->description); 

     $row = 13; 
     foreach($data as $key => $temp) { 
      $col = 1; 
      foreach(array_keys($temp) as $value) { 
       $file->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $temp[$value]); 
       $col++; 
      } 
      $row++; 
     } 
    })->export('xls'); 
} 

l'idea è make e array e quindi allegare utilizzando il metodo setCellValueByColumnAndRow

Problemi correlati