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小技巧搜集,每个PHPer都来露一手
Jan 02 PHP
php实现mysql同步的实现方法
Oct 21 PHP
PHP文件读写操作之文件写入代码
Jan 13 PHP
php中记录用户访问过的产品,在cookie记录产品id,id取得产品信息
May 04 PHP
PHP插入排序实现代码
Apr 04 PHP
PHP 读取Postgresql中的数组
Apr 14 PHP
ThinkPHP实现多数据库连接的解决方法
Jul 01 PHP
PHP中ini_set与ini_get用法实例
Nov 04 PHP
php基本函数汇总
Jul 09 PHP
示例详解Laravel重置密码代码重构
Aug 10 PHP
完美解决Thinkphp3.2中插入相同数据的问题
Aug 01 PHP
PHP 范围解析操作符(::)用法分析【访问静态成员和类常量】
Apr 14 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检测数组长度函数sizeof与count用法
2014/11/17 PHP
php抓取并保存网站图片的实现代码
2015/10/28 PHP
实例详解PHP中html word 互转的方法
2016/01/28 PHP
PHP获取客户端及服务器端IP的封装类
2016/07/21 PHP
php实现生成带二维码图片并强制下载功能
2018/02/24 PHP
JavaScript CSS修改学习第三章 修改样式表
2010/02/19 Javascript
JQuery跨Iframe选择实现代码
2010/08/19 Javascript
window.location.hash 使用说明
2010/11/08 Javascript
JS实现简单的顶部定时关闭层效果
2014/06/15 Javascript
js动态生成Html元素实现Post操作(createElement)
2015/09/14 Javascript
JS实现将Asp.Net的DateTime Json类型转换为标准时间的方法
2016/08/02 Javascript
vue制作加载更多功能的正确打开方式
2016/10/12 Javascript
jq checkbox 的全选并ajax传参的实例
2017/04/01 Javascript
Angular.js中angular-ui-router的简单实践
2017/07/18 Javascript
Angular网络请求的封装方法
2018/05/22 Javascript
js实现图片放大并跟随鼠标移动特效
2019/01/18 Javascript
使用Angular自定义字段校验指令的方法示例
2019/02/01 Javascript
Vue自定义组件的四种方式示例详解
2020/02/28 Javascript
用python记录运行pid,并在需要时kill掉它们的实例
2017/01/16 Python
Python结合ImageMagick实现多张图片合并为一个pdf文件的方法
2018/04/24 Python
Python PyCharm如何进行断点调试
2019/07/05 Python
ansible动态Inventory主机清单配置遇到的坑
2020/01/19 Python
Python找出列表中出现次数最多的元素三种方式
2020/02/24 Python
Python matplotlib可视化实例解析
2020/06/01 Python
python性能测试工具locust的使用
2020/12/28 Python
Python实现邮件发送的详细设置方法(遇到问题)
2021/01/18 Python
解析HTML5的存储功能和web SQL的相关操作方法
2016/02/19 HTML / CSS
Zooplus葡萄牙:欧洲领先的网上宠物商店
2018/07/01 全球购物
新西兰最大的连锁超市:Countdown
2020/06/04 全球购物
售后求职信范文
2014/03/15 职场文书
中学生操行评语大全
2014/04/24 职场文书
活动总结报告范文
2014/05/04 职场文书
关于PostgreSQL JSONB的匹配和交集问题
2021/09/14 PostgreSQL
Python Matplotlib绘制条形图的全过程
2021/10/24 Python
《废话连篇——致新手》——chinapizza
2022/04/05 无线电
Python中re模块的元字符使用小结
2022/04/07 Python