問題:
laravel-admin 中頂部導(dǎo)出數(shù)據(jù)為csv格式,打開后直接亂碼不知道如何解決囚痴,可能是字符集問題遂填,代碼里面默認(rèn)是utf8格式修改為gbk依然亂碼!
可以通過phpexcel導(dǎo)出數(shù)據(jù)窝稿,解決導(dǎo)出亂碼的問題。
安裝phpexcel的擴(kuò)展
1.在laravel項(xiàng)目的根目錄安裝composer 依賴谊路。
composer require maatwebsite/excel ~2.1.0
2.在config/app.php中注冊(cè)服務(wù)提供者到providers數(shù)組:
Maatwebsite\Excel\ExcelServiceProvider::class,
3.同樣在config/app.php中注冊(cè)門面到aliases數(shù)組:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
修改導(dǎo)出文件的設(shè)置
1.文件路徑
vendor/encore/laravel-admin/src/Grid/Exporters/CsvExporter.php
頭部增加
use Excel;
對(duì)應(yīng)的函數(shù)
export()修改為
public function export(){
$tables = Common::tablesname();
if(key_exists($this->getTable(),$tables)){
$filename = $tables[$this->getTable()];
}else{
$filename = $this->getTable();
}
$titles = Common::showcolumns($this->getTable());
$handle = [];
$types = Common::tablesnametype($this->getTable());
//下面主要是導(dǎo)入數(shù)據(jù)的操作 可以根據(jù)自己邏輯修改
$this->chunk(function ($records) use (&$handle, &$titles,$types) {
if (empty($titles)) {
$titles = $this->getHeaderRowFromRecords($records);
}
$handle[] = $titles;
$mapfilter = Common::export_filter($types);
foreach ($records as $record) {
$newrecord = [];
$record = $this->getFormattedRecord($record);
foreach($titles as $tk =>$tv){
//dd($record);
if(key_exists(strtolower($tk),$record)){
$newrecord[$tk] = $record[strtolower($tk)];
}else{
$newrecord[$tk] = '';
}
}
$handle[] = $newrecord;
});
//把數(shù)據(jù)寫入到excel中
$cellData = $handle;
Excel::create($filename,function($excel) use ($cellData){
$excel->sheet('數(shù)據(jù)', function($sheet) use ($cellData){
$sheet->rows($cellData);
});
})->export('xls');
}