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学习之php4与php5之间会穿梭一点点感悟
May 03 PHP
flash用php连接数据库的代码
Apr 21 PHP
php文件打包 下载之使用PHP自带的ZipArchive压缩文件并下载打包好的文件
Jun 13 PHP
php中防止SQL注入的最佳解决方法
Apr 25 PHP
基于php split()函数的用法详解
Jun 05 PHP
php数组查找函数in_array()、array_search()、array_key_exists()使用实例
Apr 29 PHP
php中mysql操作buffer用法详解
Mar 19 PHP
PHP整合七牛实现上传文件
Jul 03 PHP
微信支付扫码支付php版
Jul 22 PHP
form自动提交实例讲解
Jul 10 PHP
PHP常量define和const的区别详解
May 18 PHP
php实现快速对二维数组某一列进行组装的方法小结
Dec 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&mysql(一)
2006/10/09 PHP
php面向对象全攻略 (十五) 多态的应用
2009/09/30 PHP
php中对2个数组相加的函数
2011/06/24 PHP
php 调试利器debug_print_backtrace()
2012/07/23 PHP
微信公众号模板消息群发php代码示例
2016/12/29 PHP
PHP使用imagick扩展实现合并图像的方法
2017/04/25 PHP
PHP-FPM 的管理和配置详解
2019/02/17 PHP
让JavaScript 轻松支持函数重载 (Part 1 - 设计)
2009/08/04 Javascript
jquery ajax 调用失败的原因示例介绍
2013/09/27 Javascript
元素未显示设置width/height时IE中使用currentStyle获取为auto
2014/05/04 Javascript
javascript 面向对象封装与继承
2014/11/27 Javascript
jQuery插件Easyui设置datagrid的pageNumber导致两次请求问题的解决方法
2016/08/06 Javascript
BootStrapTable 单选及取值的实现方法
2017/01/10 Javascript
jQuery实现获取h1-h6标题元素值的方法
2017/03/06 Javascript
AngularJS 霸道的过滤器小结
2017/04/26 Javascript
Vue Element使用icon图标教程详解(第三方)
2018/02/07 Javascript
解决Vue2.0中使用less给元素添加背景图片出现的问题
2018/09/03 Javascript
关于vue-cli 3配置打包优化要点(推荐)
2019/04/22 Javascript
小程序云开发之用户注册登录
2019/05/18 Javascript
vue实现带复选框的树形菜单
2019/05/27 Javascript
vue开发简单上传图片功能
2020/06/30 Javascript
[02:19]2018年度DOTA2最佳核心位选手-完美盛典
2018/12/17 DOTA
Python实现批量下载图片的方法
2015/07/08 Python
在Django的form中使用CSS进行设计的方法
2015/07/18 Python
整理Python 常用string函数(收藏)
2016/05/30 Python
python使用turtle绘制国际象棋棋盘
2019/05/23 Python
python使用OpenCV模块实现图像的融合示例代码
2020/04/10 Python
Python WebSocket长连接心跳与短连接的示例
2020/11/24 Python
Html5 Canvas 实现一个“刮刮乐”游戏
2019/09/05 HTML / CSS
美国著名的户外用品品牌:L.L.Bean
2018/01/05 全球购物
你们项目是如何进行变更控制的
2015/08/26 面试题
高中校园广播稿
2014/01/11 职场文书
关于圣诞节的广播稿
2014/01/26 职场文书
深入开展党的群众路线教育实践活动方案
2014/02/04 职场文书
百年校庆节目主持词
2014/03/27 职场文书
人民检察院起诉书
2015/05/20 职场文书