1. 程式人生 > 其它 >php 陣列匯出csv_在PHP中建立和編輯Excel電子表格

php 陣列匯出csv_在PHP中建立和編輯Excel電子表格

技術標籤:php 陣列匯出csv

要使用純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'); 

下一步

PHPExcel提供了本教程中未提及的許多功能,例如函式,計算和圖表。閱讀PHPExcel 文件 以瞭解有關這些的更多資訊。

以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務程式碼寫多了沒有方向感,不知道該從那裡入手去提升,對此我整理了一些資料,包括但不限於:分散式架構、高可擴充套件、高效能、高併發、伺服器效能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell指令碼、Docker、微服務、Nginx等多個知識點高階進階乾貨需要的可以免費分享給大家,需要

PHP進階架構師>>>視訊、面試文件免費獲取​docs.qq.com 20f3cf4b3eef5805b0bdd197766b6289.png

或 者關注咱們下面的知乎專欄

PHP大神進階​zhuanlan.zhihu.com 08d58bf20d421b8b2d4b1f452c7a96b9.png