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 相关文章推荐
综合图片计数器
Oct 09 PHP
php调用c接口无错版介绍
Mar 11 PHP
php获取mysql字段名称和其它信息的例子
Apr 14 PHP
PHP计算一年多少个星期和每周的开始和结束日期
Jul 01 PHP
PHP基于文件存储实现缓存的方法
Jul 20 PHP
Laravel实现定时任务的示例代码
Aug 10 PHP
PHP回调函数与匿名函数实例详解
Aug 16 PHP
ThinkPHP5.0框架验证码功能实现方法【基于第三方扩展包】
Mar 11 PHP
php微信扫码支付 php公众号支付
Mar 24 PHP
Yii2处理密码加密及验证的方法
May 12 PHP
在Laravel 中实现是否关注的示例
Oct 22 PHP
phpquery中文手册
Mar 18 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
与数据库连接
2006/10/09 PHP
用 PHP5 轻松解析 XML
2006/12/04 PHP
php中的观察者模式
2010/03/24 PHP
怎样给PHP源代码加密?PHP二进制加密与解密的解决办法
2013/04/22 PHP
分享50个提高PHP执行效率的技巧
2015/12/26 PHP
PHP实现数组转JSon和JSon转数组的方法示例
2018/06/14 PHP
基于jquery的使ListNav兼容中文首字拼音排序的实现代码
2011/07/10 Javascript
解决火狐浏览器下JS setTimeout函数不兼容失效不执行的方法
2012/11/14 Javascript
Js 获取Gridview选中行的内容操作步骤
2013/02/05 Javascript
jQuery获取checkboxlist的value值的方法
2015/09/27 Javascript
javascript创建对象、对象继承的实用方式详解
2016/03/08 Javascript
Bootstrap3制作图片轮播效果
2016/05/12 Javascript
Javascript在IE和Firefox浏览器常见兼容性问题总结
2016/08/03 Javascript
详解AngularJS ng-class样式切换
2017/06/27 Javascript
javaScript中封装的各种写法示例(推荐)
2017/07/03 Javascript
Vue的路由及路由钩子函数的实现
2019/07/02 Javascript
解决vue bus.$emit触发第一次$on监听不到问题
2020/07/28 Javascript
python和pyqt实现360的CLable控件
2014/02/21 Python
Python的爬虫程序编写框架Scrapy入门学习教程
2016/07/02 Python
django+js+ajax实现刷新页面的方法
2017/05/22 Python
python登录WeChat 实现自动回复实例详解
2019/05/28 Python
Django MEDIA的配置及用法详解
2019/07/25 Python
Django多数据库的实现过程详解
2019/08/01 Python
django使用JWT保存用户登录信息
2020/04/22 Python
python实现扫雷小游戏
2020/04/24 Python
PyChon中关于Jekins的详细安装(推荐)
2020/12/28 Python
HTML5 CSS3新的WEB标准和浏览器支持
2009/07/16 HTML / CSS
美国知名的百货清仓店:Neiman Marcus Last Call
2016/08/03 全球购物
护理专业推荐信
2013/11/07 职场文书
开业庆典主持词
2014/03/21 职场文书
培训班开班仪式主持词
2014/03/28 职场文书
一体化教学实施方案
2014/05/10 职场文书
2015高考寄语集锦
2015/02/27 职场文书
爱护环境建议书
2015/09/14 职场文书
2016年社区综治宣传月活动总结
2016/03/16 职场文书
Vue.js中v-bind指令的用法介绍
2022/03/13 Vue.js