PHP中创建和编辑Excel表格的方法


Posted in PHP onSeptember 13, 2018

要使用纯PHP创建或编辑Excel电子表格,我们将使用PHPExcel库,它可以读写许多电子表格格式,包括xls,xlsx,ods和csv。在我们继续之前,仔细检查您的服务器上是否有PHP 5.2或更高版本以及安装了以下PHP扩展:php_zip,php_xml和php_gd2。

创建电子表格

创建电子表格是PHP应用程序中最常见的用例之一,用于将数据导出到Excel电子表格。查看以下代码,了解如何使用PHPExcel创建示例Excel电子表格:

// Include PHPExcel library and create its object
require('PHPExcel.php');

$phpExcel = new PHPExcel;

// Set default font to Arial
$phpExcel->getDefaultStyle()->getFont()->setName('Arial');

// Set default font size to 12
$phpExcel->getDefaultStyle()->getFont()->setSize(12);

// Set spreadsheet properties ? title, creator and description
$phpExcel ->getProperties()->setTitle("Product list");
$phpExcel ->getProperties()->setCreator("Voja Janjic");
$phpExcel ->getProperties()->setDescription("PHP Excel spreadsheet testing.");

// Create the PHPExcel spreadsheet writer object
// We will create xlsx file (Excel 2007 and above)
$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");

// When creating the writer object, the first sheet is also created
// We will get the already created sheet
$sheet = $phpExcel ->getActiveSheet();

// Set sheet title
$sheet->setTitle('My product list');

// Create spreadsheet header
$sheet ->getCell('A1')->setValue('Product');
$sheet ->getCell('B1')->setValue('Quanity');
$sheet ->getCell('C1')->setValue('Price');

// Make the header text bold and larger
$sheet->getStyle('A1:D1')->getFont()->setBold(true)->setSize(14);

// Insert product data


// Autosize the columns
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);
$sheet->getColumnDimension('C')->setAutoSize(true);

// Save the spreadsheet
$writer->save('products.xlsx');

如果要下载电子表格而不是将其保存到服务器,请执行以下操作:

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="file.xlsx"');
header('Cache-Control: max-age=0');
$writer->save('php://output');

编辑现有电子表格

在PHP中编辑电子表格与创建电子表格类似:

// Include PHPExcel library and create its object
require('PHPExcel.php');

// Load an existing spreadsheet
$phpExcel = PHPExcel_IOFactory::load('products.xlsx');

// Get the first sheet
$sheet = $phpExcel ->getActiveSheet();

// Remove 2 rows starting from the row 2
$sheet ->removeRow(2,2);

// Insert one new row before row 2
$sheet->insertNewRowBefore(2, 1);

// Create the PHPExcel spreadsheet writer object
// We will create xlsx file (Excel 2007 and above)
$writer = PHPExcel_IOFactory::createWriter($phpExcel, "Excel2007");

// Save the spreadsheet
$writer->save('products.xlsx');

准备电子表格进行打印

要准备电子表格进行打印,我们将设置纸张方向,尺寸和边距:

$sheet->getPageSetup()->setOrientation(PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE);
$sheet -> getPageSetup()->setPaperSize(PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4); 
$sheet->getPageMargins()->setTop(1);
$sheet ->getPageMargins()->setRight(0.75);
$sheet ->getPageMargins()->setLeft(0.75);
$sheet ->getPageMargins()->setBottom(1);

将PHPExcel与Laravel一起使用

PHPExcel库也可以在Laravel框架中使用。查看以下PHP包(此处)并通过Composer安装它。完成安装步骤后,您可以使用以下代码将数据从数据库导出到Excel电子表格中:

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

        // Set the title
        $excel->setTitle('Product list');
  
        // Set the creator
        $excel->setCreator('Voja Janjic');
  
        // Set description
        $excel->setDescription('PHP Excel spreadsheet testing');
  
        $excel->sheet('Products', function($sheet) {
   
                // Get data from the database
                $products = Product::all(); 
  
                // Generate header row
                $sheet->row(1, array(
                        'ID',
                        'Product',
                        'Price',
                        'Quantity',     
                ));
  
                // Generate data rows 
                $i = 2; 
                foreach($products as $product) {    
                        $sheet->row($i, array(
                                   $product->product_id,
                                   $product->product_name,
                                   $product->price,
                                   $variety->quantity,    
                        ));
   
                        $i++;
                }

        });

})->export('xlsx');
PHP 相关文章推荐
smarty 原来也不过如此~~呵呵
Nov 25 PHP
PHP写杨辉三角实例代码
Jul 17 PHP
PHP的魔术常量__METHOD__简介
Jul 08 PHP
PHP中echo,print_r与var_dump区别分析
Sep 29 PHP
PHP通过内置函数memory_get_usage()获取内存使用情况
Nov 20 PHP
php bootstrap实现简单登录
Mar 08 PHP
php通过两层过滤获取留言内容的方法
Jul 11 PHP
php添加数据到xml文件的简单例子
Sep 08 PHP
php fseek函数读取大文件两种方法
Oct 12 PHP
PHP中for循环与foreach的区别
Mar 06 PHP
YII中Ueditor富文本编辑器文件和图片上传的配置图文教程
Mar 15 PHP
thinkphp5 框架结合plupload实现图片批量上传功能示例
Apr 04 PHP
PHP通过get方法获得form表单数据方法总结
Sep 12 #PHP
php获取手机端的号码以及ip地址实例代码
Sep 12 #PHP
详解php用static方法的原因
Sep 12 #PHP
php实现数字补零的方法总结
Sep 12 #PHP
php使用QueryList轻松采集js动态渲染页面方法
Sep 11 #PHP
Yii2结合Workerman的websocket示例详解
Sep 10 #PHP
PHP按符号截取字符串的指定部分的实现方法
Sep 10 #PHP
You might like
php 广告调用类代码(支持Flash调用)
2011/08/11 PHP
Zend Framework教程之Zend_Controller_Plugin插件用法详解
2016/03/07 PHP
PHP实现的大文件切割与合并功能示例
2018/04/10 PHP
PHPstorm启用自动换行的方法详解(IDE)
2020/09/17 PHP
jQuery的实现原理的模拟代码 -4 重要的扩展函数 extend
2010/08/03 Javascript
使用jQuery.fn自定义jQuery翻页插件
2013/01/20 Javascript
nullJavascript中创建对象的五种方法实例
2013/05/07 Javascript
js window.print实现打印特定控件或内容
2013/09/16 Javascript
JavaScript弹出新窗口并控制窗口移动到指定位置的方法
2015/04/06 Javascript
Nodejs中 npm常用命令详解
2016/07/04 NodeJs
关于js二维数组和多维数组的定义声明(详解)
2016/10/02 Javascript
JavaScript  event对象整理及详细介绍
2016/10/10 Javascript
浅谈jquery中next与siblings的区别
2016/10/27 Javascript
JS动态生成年份和月份实例代码
2017/02/04 Javascript
vue2.0 中#$emit,$on的使用详解
2017/06/07 Javascript
通过jquery的ajax请求本地的json文件方法
2018/08/08 jQuery
利用python批量给云主机配置安全组的方法教程
2017/06/21 Python
Python numpy实现数组合并实例(vstack,hstack)
2018/01/09 Python
python实现自动解数独小程序
2019/01/21 Python
python调用pyaudio使用麦克风录制wav声音文件的教程
2019/06/26 Python
Python qqbot 实现qq机器人的示例代码
2019/07/11 Python
利用Python校准本地时间的方法教程
2019/10/31 Python
HTML5如何实现元素拖拽
2016/03/11 HTML / CSS
HTML5 video视频字幕的使用和制作方法
2018/05/03 HTML / CSS
吉列剃须刀英国官网:Gillette英国
2019/03/28 全球购物
全球才华横溢工匠的家居装饰、珠宝和礼物:NOVICA
2021/01/22 全球购物
《日月潭》教学反思
2014/02/28 职场文书
电子商务专业毕业生自荐书
2014/06/22 职场文书
部队反四风对照检查材料
2014/09/26 职场文书
交通事故调解协议书
2015/05/20 职场文书
新年晚会开场白
2015/05/29 职场文书
Python如何使用logging为Flask增加logid
2021/03/30 Python
只需要100行Python代码就可以实现的贪吃蛇小游戏
2021/05/27 Python
SQL实现LeetCode(175.联合两表)
2021/08/04 MySQL
springboot中rabbitmq实现消息可靠性机制详解
2021/09/25 Java/Android
Redis之RedisTemplate配置方式(序列和反序列化)
2022/03/13 Redis