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生成便于打印的网页
Oct 09 PHP
PHP实现多服务器session共享之NFS共享的方法
Mar 16 PHP
PHP实现定时生成HTML网站首页实例代码
Nov 20 PHP
PHP中文件读、写、删的操作(PHP中对文件和目录操作)
Mar 06 PHP
php foreach循环中使用引用的问题
Nov 06 PHP
ThinkPHP基本的增删查改操作实例教程
Aug 22 PHP
PHP中使用php5-ffmpeg撷取视频图片实例
Jan 07 PHP
php递归删除指定文件夹的方法小结
Apr 20 PHP
PHP实现通过get方式识别用户发送邮件的方法
Jul 16 PHP
基于ThinkPHP实现批量删除
Dec 18 PHP
Yii框架数据模型的验证规则rules()被执行的方法
Dec 02 PHP
laravel如何开启跨域功能示例详解
Aug 31 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
一些操作和快捷键的理解和讨论
2020/03/04 星际争霸
层叠菜单的动态生成
2006/10/09 PHP
php+mysql实现数据库随机重排实例
2014/10/17 PHP
php模仿asp Application对象在线人数统计实现方法
2015/01/04 PHP
PHP中的print_r 与 var_dump 输出数组
2016/06/13 PHP
PHP array_reduce()函数的应用解析
2018/10/28 PHP
jquery的Theme和Theme Switcher使用小结
2010/09/08 Javascript
js判断输入字符串是否为空、空格、null的方法总结
2016/06/14 Javascript
自定义PC微信扫码登录样式写法
2017/12/12 Javascript
vue.js整合vux中的上拉加载下拉刷新实例教程
2018/01/09 Javascript
浅谈vue单一组件下动态修改数据时的全部重渲染
2018/03/01 Javascript
在小程序中推送模板消息的实现方法
2019/07/22 Javascript
vue倒计时刷新页面不会从头开始的解决方法
2020/03/03 Javascript
使用Python脚本将绝对url替换为相对url的教程
2015/04/24 Python
详解Python实现多进程异步事件驱动引擎
2017/08/25 Python
python中利用Future对象回调别的函数示例代码
2017/09/07 Python
Python+matplotlib实现华丽的文本框演示代码
2018/01/22 Python
浅谈Python Opencv中gamma变换的使用详解
2018/04/02 Python
python指定写入文件时的编码格式方法
2018/06/07 Python
Python实现的微信好友数据分析功能示例
2018/06/21 Python
Python 判断图像是否读取成功的方法
2019/01/26 Python
python实现微信小程序用户登录、模板推送
2019/08/28 Python
Python多线程实现支付模拟请求过程解析
2020/04/21 Python
Anaconda+vscode+pytorch环境搭建过程详解
2020/05/25 Python
Django实现前台上传并显示图片功能
2020/05/29 Python
如何在Python对Excel进行读取
2020/06/04 Python
容易被忽略的Python内置类型
2020/09/03 Python
Python列表的深复制和浅复制示例详解
2021/02/12 Python
惊艳的手工时装首饰:Migonne Gavigan
2018/02/23 全球购物
网络工程师的自我评价
2013/10/02 职场文书
《花的勇气》教后反思
2014/02/12 职场文书
高三励志标语
2014/06/05 职场文书
购房委托书
2014/10/15 职场文书
小学教师先进事迹材料
2014/12/15 职场文书
独生子女证明范本
2015/06/19 职场文书
nginx实现发布静态资源的方法
2021/03/31 Servers