要安裝和配置PHP的ExcelWriter擴展,請按照以下步驟操作:
確保您的服務器滿足以下要求:
安裝libxlsxwriter庫:
sudo apt-get install libxlsxwriter-dev
sudo yum install libxlsxwriter-devel
安裝PHP ExcelWriter擴展:
sudo apt-get install php5.x-xlsxwriter
sudo yum install php5x-xlsxwriter
ext
目錄下。然后,在php.ini
文件中添加以下行:extension=php_xlsxwriter.dll
配置PHP ExcelWriter擴展:
php_xlsxwriter.php
文件,如下所示:require_once 'php_xlsxwriter.php';
new XLSXWriter()
創建一個新的ExcelWriter對象,并設置相關選項,例如文件名、作者等。writeSheet()
、writeRow()
、writeCell()
等方法向Excel文件中添加數據。close()
方法關閉Excel文件并保存更改。示例代碼:
<?php
require_once 'php_xlsxwriter.php';
// 創建一個新的ExcelWriter對象
$workbook = new XLSXWriter();
$worksheet = $workbook->add_worksheet();
// 設置表頭樣式
$header_font = array(
'bold' => true,
'bg' => '#D7E4BC',
'border' => 1,
'align' => 'center',
'font' => 'Arial',
'size' => 12,
);
// 寫入表頭
$headers = array('Name', 'Age', 'Country');
foreach ($headers as $col_num => $header) {
$worksheet->write($row, $col_num, $header, $header_font);
}
// 寫入數據
$data = array(
array('John', 28, 'USA'),
array('Jane', 25, 'Canada'),
array('Mike', 30, 'UK'),
);
foreach ($data as $row_num => $row) {
foreach ($row as $col_num => $cell_value) {
$worksheet->write($row_num + 1, $col_num, $cell_value);
}
}
// 關閉Excel文件并保存更改
$workbook->close();
?>
按照以上步驟操作后,您應該已經成功安裝并配置了PHP ExcelWriter擴展。現在您可以在PHP代碼中使用它來創建和操作Excel文件了。