Laravel-Excel导出功能文档

简单Excel导出

基础功能

使用create方法快速一个文件,文件名作为第一个参数

Excel::create('Filename');

手动创建文件,使用LaravelExcelWriter实例作为回调函数的参数

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

    // Call writer methods here

});

设置属性

可以在闭包中修改一些属性,很多属性可在配置文件中设置默认值 config/excel.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');

});

导出

可以使用->export($ext)->download($ext)下载创建的文件

导出到Excel5 (xls)
Excel::create('Filename', function($excel) {

})->export('xls');

// or
->download('xls');
导出到Excel2007 (xlsx)

->export('xlsx');

// or
->download('xlsx');
导出到CSV (csv)

->export('csv');

// or
->download('csv');
导出到PDF

如果要导出文件到pdf,需要使用composer安装如下扩展之一

"dompdf/dompdf": "~0.6.1",

"mpdf/mpdf": "~6.1"

"tecnick.com/tcpdf": "~6.0.0"

同时需要设置config文件export.pdf.driver

NewExcelFile依赖注入

为了紧跟laravel5的步伐,引入NewExcelFile依赖注入

NewExcelFile 类

NewExcelFile是对新的Excel文件的封装,你可以在内部使用getFilename()声明文件名

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

    public function getFilename()
    {
        return 'filename';
    }
}

使用方法

你可以注入 NewExcelFile类到控制器的构造方法或普通方法中。

class ExampleController extends Controller {

    public function exportUserList(UserListExport $export)
    {
        // work on the export
        return $export->sheet('sheetName', function($sheet)
        {

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

}

export句柄

为了完全从你的控制器中解耦 Excel-export代码,你可以使用export句柄

class ExampleController extends Controller {

    public function exportUserList(UserListExport $export)
    {
        // Handle the export
        $export->handleExport();
    }

}

handleExport()方法可以动态的绑定

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($ext, $path = false, $returnInfo = false)或者->save()方法将创建的文件保存到服务器

保存文件到默认的storage目录

默认情况下,导出的文件会存储到storage/exports文件夹下,这个配置被设置在config文件export模块中

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

    // Set sheets

})->store('xls');

保存文件到自定义目录

如果需要导出文件到自定义目录,可以设置store函数的第二个参数

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

保存到服务器并导出文件

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

保存并返回storage信息

如果你想返回storage信息,可是设置store的第三个参数或者到配置文件中修改

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

Key

Explanation

full

文件路径(包括文件名)

path

文件路径(不包括文件名)

file

文件名

title

文件标题

ext

文件后缀

确保你的storage目录可写

Sheets

创建一个sheet

使用->sheet('Sheetname')方法,LaravelExcelWorksheet的实例$sheet作为回调函数(闭包)的参数

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

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

        // 操作sheet

    });

})->export('xls');

创建多个sheet

你可以在创建的文件里面设置多个sheet

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

    //第一个sheet
    $excel->sheet('First sheet', function($sheet) {

    });

    //第二个sheet
    $excel->sheet('Second sheet', function($sheet) {

    });

})->export('xls');

设置属性

可以在闭包中修改一些属性,很多属性可在配置文件中设置默认值 config/excel.php

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

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

        $sheet->setOrientation('landscape');

    });

})->export('xls');

可到参考手册查询更多属性

页面默认margin

可在配置文件excel::export.sheets中设置页面默认margin,接受三个可选数值类型:bool值,单个数值,数组

也可以通过->setPageMargin()手动设置

//设置 top, right, bottom, left
$sheet->setPageMargin(array(
    0.25, 0.30, 0.25, 0.30
));

//设置所有margin
$sheet->setPageMargin(0.25);

设置密码保护sheet

可以使用$sheet->protect() 保护sheet安全

// 默认保护
$sheet->protect('password');

// 高级保护
$sheet->protect('password', function(\PHPExcel_Worksheet_Protection $protection) {
    $protection->setSort(true);
});

使用数组创建sheet

数组

在sheet闭包中使用->fromArray($source, $nullValue, $startCell, $strictNullComparison, $headingGeneration)创建文件

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

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

        $sheet->fromArray(array(
            array('data1', 'data2'),
            array('data3', 'data4')
        ));

    });

})->export('xls');

当然你也可以使用 -with()

$sheet->with(array(
    array('data1', 'data2'),
    array('data3', 'data4')
));

如果你想通过闭包传递变量,使用use($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');

空值比较

默认情况下,数值0会展示成一个空白单元格,你可以通过传递第四个参数来改变这种默认行为

// 这样0就会原样展示,而不是空白单元格
$sheet->fromArray($data, null, 'A1', true);

如果想改变默认行为,可以去修改配置文件对应属性 excel::export.sheets.strictNullComparison

Eloquent model

你也可以使用->fromModel($model)去导出文件,$model是Eloquent model的实例,这个方法接收和fromArray相同的参数

自动产生表头

默认导出的文件中,会使用数组Array(或者model的属性名)作为第一行(表头),你可以在配置文件中修改这一默认行为

excel::export.generate_heading_by_indices,或者传递第5个参数,如下

// 导出文件不会自动产生表头
$sheet->fromArray($data, null, 'A1', false, false);

行操作

操作固定行

设置单行多个单元格数值

/ 操作第一行
$sheet->row(1, array(
     'test1', 'test2'
));

// 操作第二行
$sheet->row(2, array(
    'test3', 'test4'
));
同时操作单行多个单元格

// 设置第一行背景为黑色
$sheet->row(1, function($row) {

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

});

向后插入一行

// 第二行后插入一行
$sheet->appendRow(2, array(
    'appended', 'appended'
));

// 最后一行后插入一行
$sheet->appendRow(array(
    'appended', 'appended'
));

向前插入一行

// 第一行前插入一行
$sheet->prependRow(1, array(
    'prepended', 'prepended'
));

// 插入行到第一行
$sheet->prependRow(array(
    'prepended', 'prepended'
));

向后插入多行

// 插入多行
$sheet->rows(array(
    array('test1', 'test2'),
    array('test3', 'test4')
));

// 插入多行
$sheet->rows(array(
    array('test5', 'test6'),
    array('test7', 'test8')
));

单元格操作

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

    // 操作单个单元格
    $cell->setValue('data1');

});

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

    // 批量操作单元格

});

设置背景

可以使用->setBackground($color, $type, $colorType)设置单元格背景

// 设置多个单元格背景为黑色
$cells->setBackground('#000000');

设置字体

// 设置字体颜色
$cells->setFontColor('#ffffff');

// 设置字体类型
$cells->setFontFamily('Calibri');

// 设置字体大小
$cells->setFontSize(16);

// 设置是否加粗
$cells->setFontWeight('bold');

// 设置字体
$cells->setFont(array(
    'family'     => 'Calibri',
    'size'       => '16',
    'bold'       =>  true
));

设置边框

// 设置4个边框 (top, right, bottom, left)
$cells->setBorder('solid', 'none', 'none', 'solid');

// 设置边框(数组形式)
$cells->setBorder(array(
    'top'   => array(
        'style' => 'solid'
    ),
));

设置水平位置

// 设置水平居中
$cells->setAlignment('center');

设置垂直位置

//设置垂直居中
 $cells->setValignment('center');

Sheet样式

普通样式

如果你想改变sheet的样式(并非某个或具体某些单元格),你可以使用->setStyle()方法

// 使用->setStyle()设置字体
$sheet->setStyle(array(
    'font' => array(
        'name'      =>  'Calibri',
        'size'      =>  15,
        'bold'      =>  true
    )
));

字体

使用->setFont($array)设置当前sheet的字体样式

$sheet->setFont(array(
    'family'     => 'Calibri',
    'size'       => '15',
    'bold'       => true
));

分别设置

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

// 字体大小
$sheet->setFontSize(15);

// 字体加粗
$sheet->setFontBold(true);

边框

可以设置当前sheet的边框,如下:

// 设置当前sheet的所有边框
$sheet->setAllBorders('thin');

// 设置某个单元格的边框
$sheet->setBorder('A1', 'thin');

// 批量设置单元格边框
$sheet->setBorder('A1:F10', 'thin');

更多边框属性设置参见手册

冻结行

如果你想冻结某个单元格、行或者列,操作方法如下:

// 冻结第一行
$sheet->freezeFirstRow();

// 冻结第一列
$sheet->freezeFirstColumn();

// 冻结第一行和第一列
$sheet->freezeFirstRowAndColumn();

// 冻结A2单元格
$sheet->setFreeze('A2');

自动过滤

使用>setAutoFilter($range = false)方法进行自动过滤

// 设置整个sheet自动过滤
$sheet->setAutoFilter();

// 设置某个单元格范围进行自动过滤
$sheet->setAutoFilter('A1:E10');

单元格大小

设置列宽

使用->setWidth($cell, $width)设置列宽

// 设置单列宽度
$sheet->setWidth('A', 5);

// 同时设置多列宽度
$sheet->setWidth(array(
    'A'     =>  5,
    'B'     =>  10
));

设置行高

使用->setHeight($row, $height)设置行高

// 设置单行高度
$sheet->setHeight(1, 50);

// 同时设置多行高度
$sheet->setHeight(array(
    1     =>  50,
    2     =>  25
));

设置单元格大小

使用->setSize($cell, $width, $height)设置单元格大小

// 设置A1单元格大小
$sheet->setSize('A1', 500, 50);

$sheet->setSize(array(
    'A1' => array(
        'width'     => 50,
        'height'    => 500
    )
));

大小自适应

默认情况下导出的文件是大小自适应的,如果你想改变这一默认行为,可以修改config配置文件,或者如下设置

// 设置sheet大小自适应
$sheet->setAutoSize(true);

// 禁用sheet大小自适应
$sheet->setAutoSize(false);

// 禁止指定行自适应大小
$sheet->setAutoSize(array(
    'A', 'C'
));

默认的配置可见 export.confg

合并单元格

合并多个单元格

可以使用->mergeCells($range)合并多个单元格

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

合并行和列

使用->setMergeColumn($array)合并行或列

$sheet->setMergeColumn(array(
    'columns' => array('A','B','C','D'),
    'rows' => array(
        array(2,3),
        array(5,11),
    )
));

列格式化

使用->setColumnFormat($array),告诉Excel怎样格式化固定的列

// 设置列格式为百分比
$sheet->setColumnFormat(array(
    'C' => '0%'
));

// 设置列单元格4位数字
$sheet->setColumnFormat(array(
    'A2:K2' => '0000'
));

// 同时设置多列格式
$sheet->setColumnFormat(array(
    'B' => '0',
    'D' => '0.00',
    'F' => '@',
    'F' => 'yyyy-mm-dd',
));

更多可用格式参见手册

调用PHPExcel原生方法

可在$excel和$sheet对象上调用PHPExcel的原生方法

调用Workbook方法

例如:

// 获得workbook默认样式
$excel->getDefaultStyle();

调用worksheet方法

例如:

// 保护单元格
$sheet->protectCells('A1', $password);
发布了44 篇原创文章 · 获赞 1 · 访问量 4334

猜你喜欢

转载自blog.csdn.net/zc520yzy/article/details/103186975