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 小乘法表实现代码
Jul 16 PHP
PHP GD 图像处理组件的常用函数总结
Apr 28 PHP
php统计文件大小,以GB、MB、KB、B输出
May 29 PHP
php在页面中调用fckeditor编辑器的方法
Jun 10 PHP
调试一段PHP程序时遇到的三个问题
Jan 17 PHP
解析用PHP实现var_export的详细介绍
Jun 20 PHP
PHPMailer发送HTML内容、带附件的邮件实例
Jul 01 PHP
php使用curl打开https网站的方法
Jun 17 PHP
10条php编程小技巧
Jul 07 PHP
基于PHP实现商品成交时发送短信功能
May 11 PHP
PHP递归遍历文件夹去除注释并压缩php源代码的方法示例
May 23 PHP
Yii实现微信公众号场景二维码的方法实例
Aug 30 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 字符串分割和比较
2009/10/06 PHP
创建数据库php代码 用PHP写出自己的BLOG系统
2010/04/12 PHP
php开发环境配置记录
2011/01/14 PHP
阿里云的WindowsServer2016上部署php+apache
2018/07/17 PHP
php 利用socket发送GET,POST请求的实例代码
2020/07/04 PHP
js动态往表格的td中添加图片并注册事件
2014/06/12 Javascript
js实现鼠标移到链接文字弹出一个提示层的方法
2015/05/11 Javascript
javascript实现平滑无缝滚动
2020/08/09 Javascript
Javascript将数字转化成为货币格式字符串
2016/06/22 Javascript
Angular 理解module和injector,即依赖注入
2016/09/07 Javascript
Vue.js每天必学之过滤器与自定义过滤器
2016/09/07 Javascript
JS组件系列之JS组件封装过程详解
2017/04/28 Javascript
easyui combogrid实现本地模糊搜索过滤多列
2017/05/13 Javascript
Angular实现点击按钮控制隐藏和显示功能示例
2017/12/29 Javascript
angularjs中判断ng-repeat是否迭代完的实例
2018/09/12 Javascript
基于JS开发微信网页录音功能的实例代码
2019/04/30 Javascript
js+css实现扇形导航效果
2020/08/18 Javascript
vue实现下拉菜单树
2020/10/22 Javascript
Echarts在Taro微信小程序开发中的踩坑记录
2020/11/09 Javascript
[01:26]神话结束了,却也刚刚开始——DOTA2新英雄玛尔斯驾临战场
2019/03/10 DOTA
浅谈Python的异常处理
2016/06/19 Python
Python爬虫使用脚本登录Github并查看信息
2018/07/16 Python
详细介绍Python进度条tqdm的使用
2019/07/31 Python
python sorted方法和列表使用解析
2019/11/18 Python
使用python3批量下载rbsp数据的示例代码
2019/12/20 Python
Django QuerySet查询集原理及代码实例
2020/06/13 Python
Python+Xlwings 删除Excel的行和列
2020/12/19 Python
python中numpy.empty()函数实例讲解
2021/02/05 Python
新西兰航空中国官网:Air New Zealand China
2018/07/24 全球购物
医学检验专业个人求职信范文
2013/12/04 职场文书
大学生学习2014年全国两会心得体会
2014/03/12 职场文书
小学生2014国庆节演讲稿:祖国在我心中
2014/09/21 职场文书
党支部四风整改方案
2014/10/25 职场文书
2015人事行政工作总结范文
2015/05/21 职场文书
盗窃案辩护词
2015/05/21 职场文书
python多线程方法详解
2022/01/18 Python