Laravel Excel —— Export导出

Simple Excel Export 简单的Excel导出

推荐http://www.cnblogs.com/hyfeng/articles/5038000.html

Basics 基础

A new file can be created using thecreatemethod with the filename as first parameter.

创建一个文件,使用第一个参数作为文件名。

Excel::create('Filename');

To manipulate the creation of the file you can use the callback

可以使用回调函数操作创建的文件。

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

// Call writer methods here

});

Changing properties

更改属性

There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. See  app/config/packages/maatwebsite/excel/config.php.

有几个属性可以改变    大多数设置了默认。

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

 // Set the title  设置标题

                 $excel->setTitle('Our new awesome title');

// Chain the setters  设置创作人

                    $excel->setCreator('Maatwebsite')

                              ->setCompany('Maatwebsite');

// Call them separately   设置 介绍说明

                     $excel->setDescription('A demonstration to change the file properties');

});

Go to the reference guide to see a list of available properties.

参考指南查看可用属性列表

Exporting导出

To download the created file, use->export($ext) or ->download($ext).

下载创建的excel

Export to Excel5 (xls)格式

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

})->export('xls');

// or

->download('xls');

Export to Excel2007 (xlsx)格式

->export('xlsx');

// or

->download('xlsx');

Export to CSV格式

->export('csv');

// or

->download('csv');

You can set the default enclosure and delimiter inside the config

在配置文件里设置 范围 和 定界符

Export to PDF 导出为PDF格式

To export files to pdf, you will have to include"dompdf/dompdf": "~0.6.1","mpdf/mpdf": "~5.7.3"or"tecnick.com/tcpdf": "~6.0.0"in yourcomposer.jsonand change theexport.pdf.driverconfig setting accordingly.

->export('pdf');

如果想要导出格式为PDF,则需要安装扩展

NewExcelFile injections

新的Excel文件 注入

Following the Laravel 5.0 philosophy with its new awesome FormRequest injections, we introduce you NewExcelFile injections.

NewExcelFile class

This NewExcelFile is a wrapper for a new Excel file. Inside thegetFilename()you can declare the wanted filename.

class UserListExport extends \Maatwebsite\Excel\Files\NewExcelFile {

public function getFilename()

        {

           return 'filename';

          }

}

Usage  使用 用途

You can inject these NewExcelFiles inside the __constructor or inside the method (when using Laravel 5.0), in e.g. the controller.

class ExampleController extends Controller {

public function exportUserList(UserListExport $export)

{

// work on the export

return $export->sheet('sheetName', function($sheet)

{

})->export('xls');

}

}

Export Handlers

导出事件处理器

To decouple your Excel-export code completely from the controller, you can use the export handlers.

class ExampleController extends Controller {

public function exportUserList(UserListExport $export)

{

// Handle the export

$export->handleExport();

}

}

ThehandleExport()method will dynamically call a handler class which is your class name appended withHandler

class UserListExportHandler implements \Maatwebsite\Excel\Files\ExportHandler {

public function handle(UserListExport $export)

{

// work on the export

return $export->sheet('sheetName', function($sheet)

{

})->export('xls');

}

}

Store on server   把文件保存到服务器上

To store the created file on the server, use->store($ext, $path = false, $returnInfo = false)or->save().

Normal export to default storage path

By default the file will be stored inside theapp/storage/exportsfolder, which has been defined in theexport.phpconfig file.

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

// Set sheets

})->store('xls');

Normal export to custom storage path   一般导出到自定义的路径

If you want to use a custom storage path (e.g. to separate the files per client), you can set the folder as the second parameter.

->store('xls', storage_path('excel/exports'));

Store and export  保存并导出

->store('xls')->export('xls');

Store and return storage info  保存并显示保存信息

If you want to return storage information, set the third paramter to true or change the config setting insideexport.php.

->store('xls', false, true);

KeyExplanation

fullFull path with filename

pathPath without filename

fileFilename

titleFile title

extFile extension

Make sure your storage folder iswritable!

Sheets  工作表

Creating a sheet   创建一个工作表

To create a new sheet inside our newly created file, use->sheet('Sheetname').

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

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

// Sheet manipulation

});

})->export('xls');

Creating multiple sheets   创建多个工作表

You can set as many sheets as you like inside the file:

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

// Our first sheet

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

});

// Our second sheet

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

});

})->export('xls');

Changing properties   修改属性

There are a couple of properties we can change inside the closure. Most of them are set to the config values by default. Seeapp/config/packages/maatwebsite/excel/config.php.

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

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

$sheet->setOrientation('landscape');

});

})->export('xls');

Go to the reference guide to see a list of available properties.

Default page margin    页边距  页边空白

It's possible to set the default page margin inside the config fileexcel::export.sheets. It accepts boolean, single value or array.

To manually set the page margin you can use:->setPageMargin()

// Set top, right, bottom, left

$sheet->setPageMargin(array(

0.25, 0.30, 0.25, 0.30

));

// Set all margins

$sheet->setPageMargin(0.25);

Password protecting a sheet   使用密码保护一个工作表

A sheet can be password protected with$sheet->protect():

// Default protect   默认设置

                 $sheet->protect('password');

// Advanced protect       更高级的设置

$sheet->protect('password', function(\PHPExcel_Worksheet_Protection $protection) {

              $protection->setSort(true);

});

Creating a sheet from an array      用一个数组创建一个工作表

Array

To create a new file from an array use->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration)inside the sheet closure.

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

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

                        $sheet->fromArray(array(   使用fromArray()

                                      array('data1', 'data2'),

                                      array('data3', 'data4')

                        ));

           });

})->export('xls');

Alternatively you can use->with().  或者使用 with()

$sheet->with(array(

                array('data1', 'data2'),

                array('data3', 'data4')

));

If you want to pass variables inside the closure, useuse($data)

$data = array(

             array('data1', 'data2'),

             array('data3', 'data4')

);

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

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

                    $sheet->fromArray($data);

         });

})->export('xls');

Null comparision

By default 0 is shown as an empty cell. If you want to change this behaviour, you can pass true as 4th parameter:

// Will show 0 as 0

$sheet->fromArray($data, null, 'A1', true);

To change the default behaviour, you can useexcel::export.sheets.strictNullComparisonconfig setting.

Eloquent model

It's also possible to pass an Eloquent model and export it by using->fromModel($model). The method accepts the same parameters as fromArray

Auto heading generation

By default the export will use the keys of your array (or model attribute names) as first row (header column). To change this behaviour you can edit the default config setting (excel::export.generate_heading_by_indices) or passfalseas 5th parameter:

// Won't auto generate heading columns

$sheet->fromArray($data, null, 'A1', false, false);

Row manipulation   一行发操作

Manipulate certain row   操作某一行

Change cell values

// Manipulate first row           设置第一行

$sheet->row(1, array(

'test1', 'test2'

));

// Manipulate 2nd row            设置第二行

$sheet->row(2, array(

'test3', 'test4'

));

Manipulate row cells      操作行单元格

// Set black background         设置黑色背景

$sheet->row(1, function($row) {

               // call cell manipulation methods

               $row->setBackground('#000000');

});

Append row  附加行

// Append row after row 2   第二行后添加 附加行

$sheet->appendRow(2, array(

              'appended', 'appended'

));

// Append row as very last   最后添加附加行

$sheet->appendRow(array(

              'appended', 'appended'

));

Prepend row   前置行

// Add before first row

$sheet->prependRow(1, array(

               'prepended', 'prepended'

));

// Add as very first

$sheet->prependRow(array(

                   'prepended', 'prepended'

));

Append multiple rows    附加多行

// Append multiple rows

$sheet->rows(array(

              array('test1', 'test2'),

              array('test3', 'test4')

));

// Append multiple rows

$sheet->rows(array(

                array('test5', 'test6'),

                array('test7', 'test8')

));

Cell manipulation  单元格操作

$sheet->cell('A1', function($cell) {

// manipulate the cell

});

$sheet->cells('A1:A5', function($cells) {

// manipulate the range of cells

});

Set background

To change the background of a range of cells we can use->setBackground($color, $type, $colorType)

// Set black background

$cells->setBackground('#000000');

Change fonts

// Set with font color

$cells->setFontColor('#ffffff');

// Set font family

$cells->setFontFamily('Calibri');

// Set font size

$cells->setFontSize(16);

// Set font weight to bold

$cells->setFontWeight('bold');

// Set font

$cells->setFont(array(

'family'    => 'Calibri',

'size'      => '16',

'bold'      =>  true

));

Set borders

// Set all borders (top, right, bottom, left)

$cells->setBorder('solid', 'none', 'none', 'solid');

// Set borders with array

$cells->setBorder(array(

'borders' => array(

'top'  => array(

'style' => 'solid'

),

)

));

Set horizontal alignment    设置水平对齐方式

// Set alignment to center

$cells->setAlignment('center');

Set vertical alignment    设置垂直对其方式

// Set vertical alignment to middle

$cells->setValignment('middle');

Sheet styling   工作表样式

General styling

If you want to change the general styling of your sheet (not cell or range specific), you can use the->setStyle()method.

// Set font with ->setStyle()`

$sheet->setStyle(array(

             'font' => array(

                           'name'      =>  'Calibri',

                            'size'      =>  15,

                            'bold'      =>  true

               )

));

Fonts

To change the font for the current sheet use->setFont($array):

$sheet->setFont(array(

'family'    => 'Calibri',

'size'      => '15',

'bold'      => true

));

Separate setters

// Font family

$sheet->setFontFamily('Comic Sans MS');

// Font size

$sheet->setFontSize(15);

// Font bold

$sheet->setFontBold(true);

Borders

You can set borders for the sheet, by using:

// Sets all borders

$sheet->setAllBorders('thin');

// Set border for cells

$sheet->setBorder('A1', 'thin');

// Set border for range

$sheet->setBorder('A1:F10', 'thin');

Go to the reference guide to see a list of available border styles

Freeze rows

If you want to freeze a cell, row or column, use:

// Freeze first row

$sheet->freezeFirstRow();

// Freeze the first column

$sheet->freezeFirstColumn();

// Freeze the first row and column

$sheet->freezeFirstRowAndColumn();

// Set freeze

$sheet->setFreeze('A2');

Auto filter

To enable the auto filter use->setAutoFilter($range = false).

// Auto filter for entire sheet

$sheet->setAutoFilter();

// Set auto filter for a range

$sheet->setAutoFilter('A1:E10');

Cell size

Set column width

To set the column width use->setWidth($cell, $width).

// Set width for a single column

$sheet->setWidth('A', 5);

// Set width for multiple cells

$sheet->setWidth(array(

'A'    =>  5,

'B'    =>  10

));

Set row height

To set the row height use->setHeight($row, $height).

// Set height for a single row

$sheet->setHeight(1, 50);

// Set height for multiple rows

$sheet->setHeight(array(

1    =>  50,

2    =>  25

));

Set cell size

To set the cell size use->setSize($cell, $width, $height).

// Set size for a single cell

$sheet->setSize('A1', 500, 50);

$sheet->setSize(array(

'A1' => array(

'width'    => 50

'height'    => 500,

)

));

Auto size

By default the exported file be automatically auto sized. To change this behaviour you can either change the config or use the setters:

// Set auto size for sheet

$sheet->setAutoSize(true);

// Disable auto size for sheet

$sheet->setAutoSize(false);

// Disable auto size for columns

$sheet->setAutoSize(array(

'A', 'C'

));

The default config setting can be found in:export.php.

Column merging

Merging cells

To merge a range of cells, use->mergeCells($range).

$sheet->mergeCells('A1:E1');

Merging columns and rows

To merge columns and rows, use->setMergeColumn($array).

$sheet->setMergeColumn(array(

'columns' => array('A','B','C','D'),

'rows' => array(

array(2,3),

array(5,11),

)

));

Column formatting

To tell Excel how it should interpret certain columns, you can use->setColumnFormat($array).

// Format column as percentage

$sheet->setColumnFormat(array(

'C' => '0%'

));

// Format a range with e.g. leading zeros

$sheet->setColumnFormat(array(

'A2:K2' => '0000'

));

// Set multiple column formats

$sheet->setColumnFormat(array(

'B' => '0',

'D' => '0.00',

'F' => '@',

'F' => 'yyyy-mm-dd',

));

Go to the reference guide to see a list of available formats.

Calling PHPExcel's native methods

It's possible to call all native PHPExcel methods on the$exceland$sheetobjects.

Calling Workbook methods

Example:

// Get default style for this workbook

$excel->getDefaultStyle();

Calling worksheet methods

Example:

// Protect cells

$sheet->protectCells('A1', $password);

Head over to PHPOffice to learn more about the native methods.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容