【发布时间】:2016-12-05 09:27:11
【问题描述】:
如何生成 Microsoft Office Excel 支持的 CSV 文件?
我使用 Laravel/Excel (http://www.maatwebsite.nl/laravel-excel/) 创建了 CSV,内容是日文字符。
一切都很完美,直到我使用 Microsoft Office Excel 打开 CSV,Microsoft Office Excel 无法读取日文字符,我已经在我的视图中将文本编码为 UTF-8(因为我使用 loadView() 函数创建了 CSV)
我尝试通过记事本打开 CSV 并保存它而不做任何更改,然后使用 Microsoft Office Excel 再次打开它,并显示日文字符。
它发生了什么?我用记事本打开了两个文件(默认文件和从记事本保存的 csv)并检查不同,内容文件没有不同。
我的观点:
<html>
<head>
<meta http-equiv="Content-Type" content="text/plain; charset=UTF-8" />
</head>
<body>
<table>
<thead>
<tr>
@foreach( $keys as $key )
<th>{!! $key !!}</th>
@endforeach
</tr>
</thead>
<tbody>
@foreach( $contents as $content )
<tr>
@foreach( $keys as $key )
<td>{!! $content[ $key ] !!}</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
</body>
</html>
我的控制器:
Excel::create( 'locations-' . date( 'Y-m-d' ), function ( $export_file ) {
$export_file->sheet( 'Locations', function( $sheet ) {
$sheet->loadView( 'admin.layout.export', Location::getExportData() );
} );
} )->download( $type );
位置::getExportData() :
public static function getExportData() {
$data[ 'contents' ] = [];
$data[ 'keys' ] = [
'control',
'name',
'type',
'address',
'longitude',
'latitude',
'description'
];
$count = Location::count();
if( $count > 0 ) {
$off_ex = 1000;
for( $i = 0; $i < ( $count / $off_ex ); $i++ ) {
$locations = Location::skip( $i * $off_ex )->take( $off_ex )->get();
foreach ( $locations as $key => $location ) {
$data[ 'contents' ][] = [
'control' => '',
'name' => mb_convert_encoding( $location->name, "UTF-8" ),
'type' => $location->type,
'address' => $location->address,
'longitude' => $location->longitude,
'latitude' => $location->latitude,
'description' => $location->description
];
}
}
}
return $data;
}
图片:
【问题讨论】:
-
请发布您用于生成此 csv 文件和 csv 文件本身的代码。
-
@Jerodev 更新了我的问题
标签: php excel laravel csv encoding