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实现文件安全下载
Oct 09 PHP
刚才在简化php的库,结果发现很多东西
Dec 31 PHP
php中利用post传递字符串重定向的实现代码
Apr 21 PHP
php生成图形验证码几种方法小结
Aug 15 PHP
php中将一段数据存到一个txt文件中并显示其内容
Aug 15 PHP
php实现文件下载代码分享
Aug 19 PHP
微信公众平台消息接口校验与消息接口响应实例
Dec 23 PHP
php文件系统处理方法小结
May 23 PHP
PHP设计模式之工厂模式详解
Oct 24 PHP
PHP 多任务秒级定时器的实现方法
May 13 PHP
PHP实现百度人脸识别
May 06 PHP
基于ThinkPHP5框架使用QueryList爬取并存入mysql数据库操作示例
May 25 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多用户计数器代码
2007/03/11 PHP
php下载文件的代码示例
2012/06/29 PHP
php中长文章分页显示实现代码
2012/09/29 PHP
php通过array_push()函数添加多个变量到数组末尾的方法
2015/03/18 PHP
php工具型代码之印章抠图
2018/07/18 PHP
Yii2.0实现的批量更新及批量插入功能示例
2019/01/29 PHP
js中匿名函数的N种写法
2010/09/08 Javascript
setTimeout的延时为0时多个浏览器的区别
2012/05/23 Javascript
JS+css 图片自动缩放自适应大小
2013/08/08 Javascript
js键盘上下左右键怎么触发function(实例讲解)
2013/12/14 Javascript
Jquery中Event对象属性小结
2015/02/27 Javascript
js实现每日自动换一张图片的方法
2015/05/04 Javascript
JavaScript计算某一天是星期几的方法
2015/08/05 Javascript
关于JS中match() 和 exec() 返回值和属性的测试
2016/03/21 Javascript
JQuery 设置checkbox值二次无效的解决方法
2016/07/22 Javascript
详解关于vue2.0工程发布上线操作步骤
2018/09/27 Javascript
利用JS动态生成隔行换色HTML表格的两种方法
2018/10/09 Javascript
基于vue如何发布一个npm包的方法步骤
2019/05/15 Javascript
Vue模板语法中数据绑定的实例代码
2019/05/17 Javascript
微信小程序实现类似微信点击语音播放效果
2020/03/30 Javascript
vue 使用原生组件上传图片的实例
2020/09/08 Javascript
python处理cookie详解
2014/02/07 Python
Python文档生成工具pydoc使用介绍
2015/06/02 Python
在Python的Django框架中编写编译函数
2015/07/20 Python
完美解决Pycharm无法导入包的问题 Unresolved reference
2018/05/18 Python
Windows下安装Scrapy
2018/10/17 Python
Python3使用TCP编写一个简易的文件下载器功能
2019/05/08 Python
Python3实现汉语转换为汉语拼音
2019/07/08 Python
解决python pandas读取excel中多个不同sheet表格存在的问题
2020/07/14 Python
Python爬虫之Selenium警告框(弹窗)处理
2020/12/04 Python
Pandas直接读取sql脚本的方法
2021/01/21 Python
kmart凯马特官网:美国最大的打折零售商和全球最大的批发商之一
2016/11/17 全球购物
运动会广播稿400字
2014/01/25 职场文书
英语故事演讲稿
2014/04/29 职场文书
PostgreSQL常用字符串分割函数整理汇总
2022/07/07 PostgreSQL
React更新渲染原理深入分析
2022/12/24 Javascript