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代码优化及php相关问题总结
Oct 09 PHP
PHP5 面向对象程序设计
Feb 13 PHP
php md5下16位和32位的实现代码
Apr 09 PHP
php日期转时间戳,指定日期转换成时间戳
Jul 17 PHP
解析php中session的实现原理以及大网站应用应注意的问题
Jun 17 PHP
php实现aes加密类分享
Feb 16 PHP
php调用新浪短链接API的方法
Nov 08 PHP
smarty内置函数config_load用法实例
Jan 22 PHP
php usort 使用用户自定义的比较函数对二维数组中的值进行排序
May 02 PHP
laravel实现批量更新多条记录的方法示例
Oct 22 PHP
PhpStorm 如何优雅的调试Hyperf的方法步骤
Nov 24 PHP
TP5框架实现上传多张图片的方法分析
Mar 29 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实现的DateDiff和DateAdd时间函数代码分享
2014/08/16 PHP
php基于mcrypt的加密解密实例
2014/10/27 PHP
WordPress开发中自定义菜单的相关PHP函数使用简介
2016/01/05 PHP
win10 apache配置虚拟主机后localhost无法使用的解决方法
2018/01/27 PHP
jquery Firefox3.5中操作select的问题
2009/07/10 Javascript
JavaScript中的undefined学习总结
2013/11/30 Javascript
调用DOM对象的focus使文本框获得焦点
2014/02/19 Javascript
基于JavaScript如何实现私有成员的语法特征及私有成员的实现方式
2015/10/28 Javascript
js编写一个简单的产品放大效果代码
2016/06/27 Javascript
Javascript实现倒计时时差效果
2017/05/18 Javascript
JavaScript生成图形验证码
2020/08/24 Javascript
NVM安装nodejs的方法实用步骤
2019/01/16 NodeJs
原生JS实现顶部导航栏显示按钮+搜索框功能
2019/12/25 Javascript
js函数和this用法实例分析
2020/03/13 Javascript
[04:17]DOTA2完美盛典,rOtk、BurNIng携手巴图演唱《倔强》
2017/11/28 DOTA
python 中文字符串的处理实现代码
2009/10/25 Python
Python实现计算最小编辑距离
2016/03/17 Python
python TCP Socket的粘包和分包的处理详解
2018/02/09 Python
python 匹配url中是否存在IP地址的方法
2018/06/04 Python
python3使用flask编写注册post接口的方法
2018/12/28 Python
Pycharm中如何关掉python console
2020/10/27 Python
20行代码教你用python给证件照换底色的方法示例
2021/02/05 Python
全球知名旅游社区法国站点:TripAdvisor法国
2016/08/03 全球购物
英国高端食品和葡萄酒超市:Waitrose
2016/08/23 全球购物
Ivory Isle Designs美国/加拿大:婚礼和活动文具公司
2018/08/21 全球购物
广告学专业毕业生自荐信
2013/09/24 职场文书
幼儿园中班教学反思
2014/02/10 职场文书
银行员工犯错检讨书
2014/09/16 职场文书
个人委托书怎么写
2014/09/17 职场文书
2014年前台接待工作总结
2014/12/05 职场文书
2014年后勤工作总结范文
2014/12/16 职场文书
项目经理岗位职责
2015/01/31 职场文书
初中英语教学随笔
2015/08/15 职场文书
幼儿园科学课教学反思
2016/03/03 职场文书
三年级作文之趣事作文
2019/11/04 职场文书
Windows Server 2016 配置 IIS 的详细步骤
2022/04/28 Servers