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 相关文章推荐
PHP静态类
Nov 25 PHP
用PHP实现多服务器共享SESSION数据的方法
Mar 16 PHP
php中sql注入漏洞示例 sql注入漏洞修复
Jan 24 PHP
php根据年月获取季度的方法
Mar 31 PHP
ThinkPHP令牌验证实例
Jun 18 PHP
PHP文件锁函数flock()详细介绍
Nov 18 PHP
php使用正则表达式获取图片url的方法
Jan 16 PHP
php中switch与ifelse的效率区别及适用情况分析
Feb 12 PHP
PHP批量查询WordPress留言者E-mail地址实现方法
Feb 15 PHP
PHP生成图像验证码的方法小结(2种方法)
Jul 18 PHP
PHP使用GD库输出汉字的方法【测试可用】
Nov 10 PHP
利用phpexcel对数据库数据的导入excel(excel筛选)、导出excel
Apr 27 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介绍篇
2010/10/26 PHP
PHP爆绝对路径方法收集整理
2012/09/17 PHP
PHP对表单提交特殊字符的过滤和处理方法汇总
2014/02/18 PHP
php编程每天必学之验证码
2016/03/03 PHP
关于PHP内置的字符串处理函数详解
2017/02/04 PHP
PHP pthreads v3下worker和pool的使用方法示例
2020/02/21 PHP
在服务端(Page.Write)调用自定义的JS方法详解
2013/08/09 Javascript
js与jquery获取父级元素,子级元素,兄弟元素的实现方法
2014/01/09 Javascript
js取值中form.all和不加all的区别介绍
2014/01/20 Javascript
jquery选择器排除某个DOM元素的方法(实例演示)
2014/04/25 Javascript
JavaScript截断字符串的方法
2015/07/15 Javascript
jQuery实现浮动层随浏览器滚动条滚动的方法
2015/09/22 Javascript
jQuery实现base64前台加密解密功能详解
2017/08/29 jQuery
VueJs监听window.resize方法示例
2018/01/17 Javascript
详解vue 自定义marquee无缝滚动组件
2019/04/09 Javascript
Node.js+ELK日志规范的实现
2019/05/23 Javascript
[02:39]DOTA2英雄基础教程 天怒法师
2013/11/29 DOTA
Windows下Anaconda的安装和简单使用方法
2018/01/04 Python
使用python-Jenkins批量创建及修改jobs操作
2020/05/12 Python
python爬取网易云音乐热歌榜实例代码
2020/08/07 Python
用 python 进行微信好友信息分析
2020/11/28 Python
MATCHESFASHION.COM美国官网:英国奢侈品零售商
2018/10/29 全球购物
JPA面试常见问题
2016/11/14 面试题
《忆江南》教学反思
2014/04/07 职场文书
毕业设计说明书
2014/05/07 职场文书
工作批评与自我批评范文
2014/10/16 职场文书
2014群众路线学习笔记
2014/11/06 职场文书
2014年班组长工作总结
2014/11/20 职场文书
2014年保险公司工作总结
2014/11/22 职场文书
医药公司采购员岗位职责
2015/04/03 职场文书
乒乓球比赛通知
2015/04/27 职场文书
交通事故赔偿起诉书
2015/05/20 职场文书
Spring boot应用启动后首次访问很慢的解决方案
2021/06/23 Java/Android
详解Go语言Slice作为函数参数的使用
2021/07/02 Golang
Python按顺序遍历并读取文件夹中文件
2022/04/29 Python
数据设计之权限的实现
2022/08/05 MySQL