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 相关文章推荐
模拟xcopy的函数
Oct 09 PHP
php自动跳转中英文页面
Jul 29 PHP
PHP中其实也可以用方法链
Nov 10 PHP
PHP5下$_SERVER变量不再受magic_quotes_gpc保护的弥补方法
Oct 31 PHP
php加水印的代码(支持半透明透明打水印,支持png透明背景)
Jan 17 PHP
深入PHP异步执行的详解
Jun 03 PHP
基于PHP常用字符串的总结(待续)
Jun 07 PHP
php用header函数实现301跳转代码实例
Nov 25 PHP
php定义参数数量可变的函数用法实例
Mar 16 PHP
Smarty foreach控制循环次数的一些方法
Jul 01 PHP
PHP设计模式之单例模式原理与实现方法分析
Apr 25 PHP
PHP根据key删除数组中指定的元素
Feb 28 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/01/05 PHP
php析构函数的简单使用说明
2015/08/24 PHP
yii2分页之实现跳转到具体某页的实例代码
2016/06/02 PHP
Laravel框架查询构造器简单示例
2019/05/08 PHP
JavaScript入门教程(7) History历史对象
2009/01/31 Javascript
Javascript 浮点运算的问题分析与解决方法
2013/08/27 Javascript
javascript通过className来获取元素的简单示例代码
2014/01/10 Javascript
jQuery实现类似老虎机滚动抽奖效果
2015/08/06 Javascript
css如何让浮动元素水平居中
2015/08/07 Javascript
javascript实现dom元素可拖动
2016/03/21 Javascript
js简单实现调整网页字体大小的方法
2016/07/23 Javascript
Bootstrap Modal对话框如何在关闭时触发事件
2016/12/02 Javascript
细说webpack源码之compile流程-入口函数run
2017/12/26 Javascript
ejsExcel模板在Vue.js项目中的实际运用
2018/01/27 Javascript
详解vue-cli 快速搭建单页应用之遇到的问题及解决办法
2018/03/01 Javascript
layui实现tab的添加拒绝重复的方法
2019/09/04 Javascript
echarts实现获取datazoom的起始值(包括x轴和y轴)
2020/07/20 Javascript
详解如何使用React Hooks请求数据并渲染
2020/10/18 Javascript
python strip()函数 介绍
2013/05/24 Python
python中如何使用正则表达式的非贪婪模式示例
2017/10/09 Python
python使用fork实现守护进程的方法
2017/11/16 Python
python实现堆和索引堆的代码示例
2018/03/19 Python
python命令行工具Click快速掌握
2019/07/04 Python
python os.fork() 循环输出方法
2019/08/08 Python
Python实现某论坛自动签到功能
2019/08/20 Python
Python定时从Mysql提取数据存入Redis的实现
2020/05/03 Python
Python dict的常用方法示例代码
2020/06/23 Python
在pycharm中使用pipenv创建虚拟环境和安装django的详细教程
2020/11/30 Python
宝塔面板出现“open_basedir restriction in effect. ”的解决方法
2021/03/14 PHP
HTML5 用动画的表现形式装载图像
2016/03/08 HTML / CSS
HTML5添加禁止缩放功能
2017/11/03 HTML / CSS
后备干部培训方案
2014/05/22 职场文书
简历自我评价:教师师德表现自我评价
2019/04/24 职场文书
Spring Boot 实现敏感词及特殊字符过滤处理
2021/06/29 Java/Android
试了下Golang实现try catch的方法
2021/07/01 Golang
六个好看实用的 HTML + CSS 后台登录入口页面
2022/04/28 HTML / CSS