PHP中创建和编辑Excel表格的方法
要使用纯PHP创建或编辑Excel电子表格,我们将使用PHPExcel库,它可以读写许多电子表格格式,包括xls,xlsx,ods和csv。在我们继续之前,仔细检查您的服务器上是否有PHP 5.2或更高版本以及安装了以下PHP扩展:php_zip,php_xml和php_gd2。 创建电子表格创建电子表格是程序中最常见的用例之一,用于将数据导出到Excel电子表格。查看以下代码,了解如何使用PHPExcel创建示例Excel电子表格: $phpExcel = new PHPExcel;
// Set default font to Arial // Set default font size to 12 // Set spreadsheet properties – title,creator and description // Create the PHPExcel spreadsheet writer object // When creating the writer object,the first sheet is also created // Set sheet title // Create spreadsheet header // Make the header text bold and larger // Insert product data // Autosize the columns // Save the spreadsheet 如果要下载电子表格而不是将其保存到服务器,请执行以下操作: save('php://output');
编辑现有电子表格在PHP中编辑电子表格与创建电子表格类似: // Load an existing spreadsheet
$phpExcel = PHPExcel_IOFactory::load('products.xlsx'); // Get the first sheet // Remove 2 rows starting from the row 2 // Insert one new row before row 2 // Create the PHPExcel spreadsheet writer object // Save the spreadsheet 准备电子表格进行打印要准备电子表格进行打印,我们将设置纸张方向,尺寸和边距: 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电子表格中: // 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'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |