Laravel Excel译文——导入

15 篇文章 0 订阅

【Laravel Excel】译文——导入

 
 

 
 

导入文件

 
 要导入一个文件,使用: ->load($filename)。配置可选。
 
 
1
2
3
4
5
Excel::load( 'file.xls' , function($reader) {
 
     // reader methods
 
});

 

 
 
 

excelfile注入

 
 Laravel 5.0后将使用新的好用的请求注入,下面为你介绍excelfile注射。
 
 
 ExcelFile 类
 

这个类是您的服务器上的文件的包装器,里面的getFile()方法将返回文件名和位置,getFilters()用来过滤,chunk过滤器如下:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
 
     public  function getFile()
     {
         return  storage_path( 'exports' ) .  '/file.csv' ;
     }
 
     public  function getFilters()
     {
         return  [
             'chunk'
         ];
     }
 
}

 

 如果你想动态过滤输入,很容易:
 
1
2
3
4
5
6
7
8
9
public  function getFile()
{
     // Import a user provided file
     $file = Input::file( 'report' );
     $filename = $ this ->doSomethingLikeUpload($file);
 
     // Return it's location
     return  $filename;
}

 

使用
 
 可以在__constructor或者方法里注入ExcelFiles(Laravel 5.0可用),等等。控制器:
 
 
1
2
3
4
5
6
7
8
9
class  ExampleController extends Controller {
 
     public  function importUserList(UserListImport $import)
     {
         // get the results
         $results = $import-> get ();
     }
 
}

 

 
 CSV设置 
 
 你可以通过可选的格式设置,如, $delimiter$enclosure 和  $lineEnding保护属性:
 
1
2
3
4
5
6
7
class  UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
 
     protected  $delimiter  =  ',' ;
     protected  $enclosure  =  '"' ;
     protected  $lineEnding =  '\r\n' ;
 
}

 

 
导入处理程序
 

完全从控制器中分离Excel导入代码,你可以使用导入处理程序。

 
1
2
3
4
5
6
7
8
9
class  ExampleController extends Controller {
 
     public  function importUserList(UserListImport $import)
     {
         // Handle the import
         $import->handleImport();
     }
 
}

 

 当你的类动附加到 Handler时, handleImport()方法会动态调用一个处理类:
 
1
2
3
4
5
6
7
8
9
class  UserListImportHandler implements \Maatwebsite\Excel\Files\ImportHandler {
 
     public  function handle(UserListImport $import)
     {
         // get the results
         $results = $import-> get ();
     }
 
}

 

 
 
 

处理导入结果

 
 得到所有表和行
 
 加载一个文件后,用 ->get()像这样得到结果:
 
1
2
3
Excel::load( 'file.xls' , function($reader) {
 
})-> get ();

 

 或者
 
1
2
3
4
5
6
7
8
9
Excel::load( 'file.xls' , function($reader) {
 
     // Getting all results
     $results = $reader-> get ();
 
     // ->all() is a wrapper for ->get() and will work the same
     $results = $reader->all();
 
});

 

 
 

根据文件的数量而定,->get() 和 ->all()将返回表或者行集合,可以在import.php里面设置'force_sheets_collection'true禁用这个功能。当设置为true时将总是返回一个表集合。

 
 
 
   表头属性
 
 默认excel文件第一行用作表头属性。
 
1
2
// Get the firstname
$row->firstname;

 

 
注:默认情况下,这些属性将被转换为一个段塞,在 excel::import.heading里可以改变默认内容,可选值有: true|false|slugged|ascii|numeric|hashed|trans|original。当 excel::import.to_ascii设置为true时,True 和 slugged 将转换为 ASCII, 可以更改默认分隔符以及内部配置。
 
 
 
集合
 
 表,行和单元格都是集合,意味着之后可以跟 ->get(),能使用所有集合默认的方法。
 
1
2
// E.g. group the results
$reader-> get ()->groupBy( 'firstname' );

 

  获得第一个表或者第一行
 
 要获得第一个表或者第一行,可以用 ->first()
 
1
$reader->first();

 

注:根据设置 'force_sheets_collection'的不同,将返回第一行或者第一个表。
 
 
 
   工作薄和表的标题
 
 用 ->getTitle()检索工作薄和表的标题。
 
 
1
2
3
4
5
6
7
8
// Get workbook title
$workbookTitle = $reader->getTitle();
 
foreach ($reader  as  $sheet)
{
     // get sheet title
     $sheetTitle = $sheet->getTitle();
}

 

 
   限制结果
 
 抓取行
 
 当你只想返回一个表里的X行时,用 ->take() 或者   ->limit()。
 
1
2
3
4
5
// You can either use ->take()
$reader->take(10);
 
// Or ->limit()
$reader->limit(10);

 

 跳过行
 
 当你想跳过一定数量的行,可以用 ->skip() 或者   ->limit(false, 10)。
 
1
2
3
4
5
6
7
8
9
10
11
// Skip 10 results
$reader->skip(10);
 
// Skip 10 results with limit, but return all other rows
$reader->limit( false , 10);
 
// Skip and take
$reader->skip(10)->take(10);
 
// Limit with skip and take
$reader->($skip, $take);

 

    修改结果
 
 当你想返回一个数组而不是一个对象时,可以用 ->toArray()
 
1
$reader->toArray();

 

 当你想返回一个对象,可以选择(代替get() 或者 all())用 ->toObject()。
 
1
$reader->toObject();

 

    显示结果
 
 可以将结果转储到可读输出,使用 ->dump() 或者   ->dd()
 
1
2
3
4
5
// Dump the results
$reader->dump();
 
// Dump results and die
$reader->dd();

 

 迭代结果
 
 可以用 ->each()迭代结果。
 
1
2
3
4
5
6
7
8
9
// Loop through all sheets
$reader->each(function($sheet) {
 
     // Loop through all rows
     $sheet->each(function($row) {
 
     });
 
});

 

 
另外,也可以用foreach迭代结果。
 
 
 

选择表和列

 
 选择一个指定表
 
 如果你想选择单个表,可以用 ->selectSheets($name),仅仅这个表被载入。
 
1
Excel::selectSheets( 'sheet1' )->load();

 

 选择多个表 
 
 如果你想选择文件里的多个表,通过在参数里传入一个数组。
 
1
Excel::selectSheets( 'sheet1' 'sheet2' )->load();

 

用索引选择表 
 
1
2
3
4
5
// First sheet
Excel::selectSheetsByIndex(0)->load();
 
// First and second sheet
Excel::selectSheetsByIndex(0, 1)->load();

 

  选择列
 
 如果只想选择一部分列,可以用 ->select($columns)或者传入一个数组到 ->get($columns)的第一个参数。
 
1
2
3
4
5
// Select
$reader-> select (array( 'firstname' 'lastname' ))-> get ();
 
// Or
$reader-> get (array( 'firstname' 'lastname' ));
 
全部 get 方法 (像 all(), first(), dump(), toArray(), ...)接受一个列的数组。
 
 
 

日期

 
 日期默认被解析为一个 Carbon object,可以在 import.php里设置 dates.enabled 为  false禁用日期格式化编译。
 

启用/禁用单一导入的日期格式,用->formatDates($boolean, $format)

 
1
2
3
4
5
6
7
8
// Format the dates
$reader->formatDates( true );
 
// Disable date formatting
$reader->formatDates( false );
 
// Format dates + set date format
$reader->formatDates( true 'Y-m-d' );

 

 

 格式化日期
 
 默认状态日期不格式化,但返回一个Carbon对象,这里有一些选项格式化他们。
 
 
 在->get()后格式化结果
 
 在循环中,你可以利用Carbon方法 ->format($dateFormat)
 
1
2
3
4
5
$rows->each(function($row) {
 
     $created_at = $row->created_at->format( 'Y-m-d' );
 
});

 

 设置一个默认日期格式
 
 
1
$reader->setDateFormat( 'Y-m-d' );

 

 设置自定义日期列
 
 没有日期格式的单元格将不被解析为日期。 强迫这种行为(或者用CSV导入)您可以手动设置这些日期列: ->setDateColumns()
 
1
2
3
4
$reader->setDateColumns(array(
     'created_at' ,
     'deleted_at'
))-> get ();

 

 
 

计算公式

 
 默认文件里的公式将被计算且返回结果,在 import.php里设置 calculate改变默认行为以达到理想状态。
 
 如果您想启用/禁用它为一个单一的导入,可以用 ->calculate($boolean)
 
1
2
3
4
5
// Enable calculation
$reader->calculate();
 
// Disable calculation
$reader->calculate( false );

 

 
 

自定认格式化值

 
 默认Laravel Excel使用PHPExcel的默认值来智能格式化的单元格值。你可以重写以取代这种行为的粘合,以满足特定需求。值粘合必须有PHPExcel_Cell_IValueBinder和一个bindValue方法。也可以扩展PHPExcel_Cell_DefaultValueBinder返回默认行为。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
use PHPExcel_Cell;
use PHPExcel_Cell_DataType;
use PHPExcel_Cell_IValueBinder;
use PHPExcel_Cell_DefaultValueBinder;
 
class  MyValueBinder extends PHPExcel_Cell_DefaultValueBinder implements PHPExcel_Cell_IValueBinder
{
     public  function bindValue(PHPExcel_Cell $cell, $value =  null )
     {
         if  (is_numeric($value))
         {
             $cell->setValueExplicit($value, PHPExcel_Cell_DataType::TYPE_NUMERIC);
 
             return  true ;
         }
 
         // else return default behavior
         return  parent::bindValue($cell, $value);
     }
}
 
$myValueBinder =  new  MyValueBinder;
 
Excel::setValueBinder($myValueBinder)->load( 'file.xls' , function($reader) {
 
     // reader methods
 
});

 

 PHPExcel_Cell_DataType 可用 TYPE_STRING, TYPE_FORMULA, TYPE_NUMERIC, TYPE_BOOL, TYPE_NULL, TYPE_INLINE 和 TYPE_ERROR。
 
 

重置默认的值或者调用Laravel Excel前设置一个自定义粘合,需要调用resetValueBinder方法。

 
1
Excel::resetValueBinder();

 

 
 

缓存和单元格缓存

 
 单元格缓存
 
 可以配置 cache.php开启单元格缓存,可以在两个动动之间选择和设置,默认开启 memory驱动。
 
 
 记住结果
 
 可以用 ->remember($minutes)记住结果,下次载入相同的文件(如果它仍然在缓存里),将返回缓存结果。
 
1
2
// Remember for 10 minutes
$results = $reader->remember(10)-> get ();

 

 
 

导入块

 
 处理大文件时,最好导入一大块数据,可以用 filter('chunk')开启,要导入块可以用 chunk($size, $callback)代替正常的 get()。第一个参数是块的尺寸,第二个参数是一个闭包将返回结果。
 
1
2
3
4
5
6
7
Excel::filter( 'chunk' )->load( 'file.csv' )->chunk(250, function($results)
{
         foreach ($results  as  $row)
         {
             // do stuff
         }
});

 

 
 ExcelFile 类例子
 
 
 当用ExcelFile注入时(在构造函数或者方法注入),可以在ExcelFile类里开启块过滤。
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class  UserListImport extends \Maatwebsite\Excel\Files\ExcelFile {
 
     public  function getFile()
     {
         return  'file.csv' ;
     }
 
     public  function getFilters()
     {
         return  [
             'chunk'
         ];
     }
 
}

 

 注入ExcelFile例子:
 
1
2
3
4
5
6
7
8
public  function importUserList(UserListImport $import)
{
     $import->chunk(250, function($results)
     {
         // do stuff
         // or return true if you want to stop importing.
     });
}

 

 
 

批量导入

 
 导入一个文件夹
 
 要导入整个文件夹(仅仅xls, xlsx 和 csv文件会被导入),第一个参数设置为文件夹。
 
1
2
3
4
5
6
7
8
9
10
11
12
Excel::batch( 'app/storage/uploads' , function($rows, $file) {
 
     // Explain the reader how it should interpret each row,
     // for every file inside the batch
     $rows->each(function($row) {
 
         // Example: dump the firstname
         dd($row->firstname);
 
     });
 
});

 

 导入多个文件
 
 也可以通过指定一个文件数组导入。
 
1
2
3
4
5
6
7
8
$files = array(
     'file1.xls' ,
     'file2.xls'
);
 
Excel::batch($files, function($rows, $file) {
 
});

 

 导入一个文件夹和多个表
 
 当文件包含多个表,还应该循环表
 
1
2
3
4
5
6
7
Excel::batch( 'app/storage/uploads' , function($sheets, $file) {
 
     $sheets->each(function($sheet) {
 
     });
 
});

 

 
 

导入设置

 
 当使用高组Excel文件(如,没有任何表头列),这些导入可能比较复杂, ->byConfig()将帮助你处理这些问题。
 
 在 excel::import.sheets里设置的例子:
 
1
2
3
4
5
6
Excel::load( 'file.xls' )->byConfig( 'excel::import.sheets' , function($sheet) {
 
     // The firstname getter will correspond with a cell coordinate set inside the config
     $firstname = $sheet->firstname;
 
});
 
注意:如果你用多个表,->byConfig将循环通过所有表,如果getters仅存在其中一个表,可以一直用->selectSheets()
 
 
 

编辑现有文件

 
 你可以编辑现有Excel文件,载入然后改性导出它们。
 
1
2
3
4
5
Excel::load( 'file.csv' , function($file) {
 
     // modify stuff
 
})->export( 'csv' );

 

 
 

转换

 
 从一个文件类型转换到另一个文件类型用 ->convert()
 
1
2
3
4
5
Excel::load( 'file.csv' , function($file) {
 
     // modify stuff
 
})->convert( 'xls' );

 

 
 
 

其他

 
 禁止使用第一行作为集合属性
 
 默认用文件的第一行作为表头( 因此,作为集合的属性名称),可以通过 import.php里的 import.heading改变。
 
 在单个导入里用 ->noHeading()
 
1
$reader->noHeading();

 

 

设置单元格名称分隔符

 
 通过在第一行列中查找默认集合属性名称,分隔翻译为: _
 
 例如: Created at -> created_at
 
 改变 import.php里的 'separator'改变默认行为,或者可以用 ->setSeparator($separator)
 
1
$reader->setSeparator( '-' );

 

 忽略空单元格
 
默认没有忽略空单元格,作为空的单元格集合
 
要改变这个默认行为,改变 import.php里的 'ignoreEmpty'或者用 ->ignoreEmpty()
 
1
$reader->ignoreEmpty();

 

 

输入编码

 

import.php里设置改变输入编码,大多数情况下UTF-8是最好的选择,当然如果你要确认输出结果是和HTML页面原编码是一致的。

可以在 ->load()里传入输入编码
 
1
2
3
4
5
6
7
// When utilising a closure, you can pass the input encoding as third parameter.
Excel::load( 'filename.csv' , function($reader) {
 
},  'UTF-8' );
 
// or without a closure, you can use it as second parameter.
Excel::load( 'filename.csv' 'UTF-8' );

 

CSV设置

 
csv.php文件里,可以修改默认设置,像 delimiter,   enclosure 和  line_ending
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值