日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

PhpOffice/PhpSpreadsheet读取和写入Excel

發(fā)布時間:2023/12/29 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 PhpOffice/PhpSpreadsheet读取和写入Excel 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

PhpSpreadsheet是一個純PHP編寫的組件庫,它使用現(xiàn)代PHP寫法,代碼質(zhì)量和性能比PHPExcel高不少,完全可以替代PHPExcel(PHPExcel已不再維護)。使用PhpSpreadsheet可以輕松讀取和寫入Excel文檔,支持Excel的所有操作。

1. 初識PhpSpreadsheet

軟件依賴

要使用PhpSpreadsheet需要滿足以下條件:

  • PHP5.6或更改版本,推薦PHP7
  • 支持php_zip擴展
  • 支持php_xml擴展
  • 支持php_gd2擴展

安裝

現(xiàn)在開始,創(chuàng)建項目目錄/PHPExcel,進入項目目錄。

使用composer安裝:

composer require phpoffice/phpspreadsheet

復(fù)制

使用

在項目目錄下新建/public目錄,在public目錄下創(chuàng)建示例文件test.php,編輯test.php,用以下代碼。

<?phprequire '../vendor/autoload.php';use PhpOffice\PhpSpreadsheet\Spreadsheet;use PhpOffice\PhpSpreadsheet\Writer\Xlsx;$spreadsheet = new Spreadsheet();$sheet = $spreadsheet->getActiveSheet();$sheet->setCellValue('A1', 'Welcome to Helloweba.');$writer = new Xlsx($spreadsheet);$writer->save('hello.xlsx');

復(fù)制

運行代碼,你會發(fā)現(xiàn)在目錄下生成一個hello.xlsx文件,打開Excel文件,你會看到Excel中的單元格A1中有“Welcome to Helloweba.”內(nèi)容。當然你可以對單元格樣式諸如顏色、背景、寬度、字體等等進行設(shè)置,這些會在接下來的幾節(jié)中講到。

PhpSpreadsheet特性

  • 支持讀取.xls,.xlsx,.html,.csv等格式文件,支持寫入導(dǎo)出.xls,.xlsx,.html,.csv,.pdf格式文件。
  • 提供豐富的API,提供單元格樣式設(shè)置、Excel表格屬性設(shè)置、圖表設(shè)置等等諸多功能。使用PhpSpreadsheet完全可以生成一個外觀結(jié)構(gòu)都滿足你的Excel表格文件。
  • 卓越的性能,尤其在PHP7上表現(xiàn)優(yōu)異,比PHPExcel強大很多。

2. 使用PhpSpreadsheet將Excel導(dǎo)入到MySQL數(shù)據(jù)庫

導(dǎo)入Excel

思路:使用PhpSpreadsheet讀取Excel表格中的有用信息,然后組裝成sql語句,最后批量插入到MySQL表中。

require 'vendor/autoload.php';include('conn.php'); //連接數(shù)據(jù)庫$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); $reader->setReadDataOnly(TRUE); $spreadsheet = $reader->load('students.xlsx'); //載入excel表格$worksheet = $spreadsheet->getActiveSheet(); $highestRow = $worksheet->getHighestRow(); // 總行數(shù) $highestColumn = $worksheet->getHighestColumn(); // 總列數(shù) $highestColumnIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColumn); // e.g. 5$lines = $highestRow - 2; if ($lines <= 0) {exit('Excel表格中沒有數(shù)據(jù)'); }$sql = "INSERT INTO `t_student` (`name`, `chinese`, `maths`, `english`) VALUES ";for ($row = 3; $row <= $highestRow; ++$row) {$name = $worksheet->getCellByColumnAndRow(1, $row)->getValue(); //姓名$chinese = $worksheet->getCellByColumnAndRow(2, $row)->getValue(); //語文$maths = $worksheet->getCellByColumnAndRow(3, $row)->getValue(); //數(shù)學(xué)$english = $worksheet->getCellByColumnAndRow(4, $row)->getValue(); //外語$sql .= "('$name','$chinese','$maths','$english'),"; } $sql = rtrim($sql, ","); //去掉最后一個,號 try {$db->query($sql);echo 'OK'; } catch (Exception $e) {echo $e->getMessage(); }

復(fù)制

3. 使用PhpSpreadsheet將數(shù)據(jù)導(dǎo)出為Excel文件

一、設(shè)置表頭

首先我們引入自動加載PhpSpreadsheet庫,然后實例化,設(shè)置工作表標題名稱為:學(xué)生成績表,接著設(shè)置表頭內(nèi)容。表頭分為兩行,第一行是表格的名稱,第二行數(shù)表格列名稱。最后我們將第一行單元格進行合并,并設(shè)置表頭內(nèi)容樣式:字體、對齊方式等。

require 'vendor/autoload.php';use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx;include('conn.php'); //連接數(shù)據(jù)庫$spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet(); //設(shè)置工作表標題名稱 $worksheet->setTitle('學(xué)生成績表');//表頭 //設(shè)置單元格內(nèi)容 $worksheet->setCellValueByColumnAndRow(1, 1, '學(xué)生成績表'); $worksheet->setCellValueByColumnAndRow(1, 2, '姓名'); $worksheet->setCellValueByColumnAndRow(2, 2, '語文'); $worksheet->setCellValueByColumnAndRow(3, 2, '數(shù)學(xué)'); $worksheet->setCellValueByColumnAndRow(4, 2, '外語'); $worksheet->setCellValueByColumnAndRow(5, 2, '總分');//合并單元格 $worksheet->mergeCells('A1:E1');$styleArray = ['font' => ['bold' => true],'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,], ]; //設(shè)置單元格樣式 $worksheet->getStyle('A1')->applyFromArray($styleArray)->getFont()->setSize(28);$worksheet->getStyle('A2:E2')->applyFromArray($styleArray)->getFont()->setSize(14);

復(fù)制

二、讀取數(shù)據(jù)

我們連接數(shù)據(jù)庫后,直接讀取學(xué)生成績表t_student,然后for循環(huán),設(shè)置每個單元格對應(yīng)的內(nèi)容,計算總成績。注意的是表格中的數(shù)據(jù)是從第3行開始,因為第1,2行是表頭占用了。

然后,我們設(shè)置整個表格樣式,給表格加上邊框,并且居中對齊。

$sql = "SELECT id,name,chinese,maths,english FROM `t_student`"; $stmt = $db->query($sql); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $len = count($rows); $j = 0; for ($i=0; $i < $len; $i++) { $j = $i + 3; //從表格第3行開始$worksheet->setCellValueByColumnAndRow(1, $j, $rows[$i]['name']);$worksheet->setCellValueByColumnAndRow(2, $j, $rows[$i]['chinese']);$worksheet->setCellValueByColumnAndRow(3, $j, $rows[$i]['maths']);$worksheet->setCellValueByColumnAndRow(4, $j, $rows[$i]['english']);$worksheet->setCellValueByColumnAndRow(5, $j, $rows[$i]['chinese'] + $rows[$i]['maths'] + $rows[$i]['english']); }$styleArrayBody = ['borders' => ['allBorders' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,'color' => ['argb' => '666666'],],],'alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,], ]; $total_rows = $len + 2; //添加所有邊框/居中 $worksheet->getStyle('A1:E'.$total_rows)->applyFromArray($styleArrayBody);

復(fù)制

三、下載保存

強制瀏覽器下載數(shù)據(jù)并保存為Excel文件

$filename = '成績表.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'.$filename.'"'); header('Cache-Control: max-age=0');$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output');

復(fù)制

三、下載保存

強制瀏覽器下載數(shù)據(jù)并保存為Excel文件

$filename = '成績表.xlsx'; header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); header('Content-Disposition: attachment;filename="'.$filename.'"'); header('Cache-Control: max-age=0');$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); $writer->save('php://output');

復(fù)制

如想要保存為.xls文件格式的話,可以改下header代碼:

$filename = '成績表.xlsx'; header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="'.$filename.'"'); header('Cache-Control: max-age=0');$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'xls'); $writer->save('php://output');

復(fù)制

4. 詳解PhpSpreadsheet設(shè)置單元格

PhpSpreadsheet提供了豐富的API接口,可以設(shè)置諸多單元格以及文檔屬性,包括樣式、圖片、日期、函數(shù)等等諸多應(yīng)用,總之你想要什么樣的Excel表格,PhpSpreadsheet都能做到。

引入了正確的文件并實例化:

use PhpOffice\PhpSpreadsheet\Spreadsheet;$spreadsheet = new Spreadsheet(); $worksheet = $spreadsheet->getActiveSheet();

復(fù)制

字體

第1行代碼將A7至B7兩單元格設(shè)置為粗體字,Arial字體,10號字;第2行代碼將B1單元格設(shè)置為粗體字。

$spreadsheet->getActiveSheet()->getStyle('A7:B7')->getFont()->setBold(true)->setName('Arial')->setSize(10);; $spreadsheet->getActiveSheet()->getStyle('B1')->getFont()->setBold(true);

復(fù)制

顏色

將文字顏色設(shè)置為紅色

$spreadsheet->getActiveSheet()->getStyle('A4')->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_RED);

復(fù)制

圖片

可以將圖片加載到Excel中

$drawing = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing(); $drawing->setName('Logo'); $drawing->setDescription('Logo'); $drawing->setPath('./images/officelogo.jpg'); $drawing->setHeight(36);

復(fù)制

列寬

將A列寬度設(shè)置為30(字符):

$spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(30);

復(fù)制

如果需要自動計算列寬,可以這樣:

$spreadsheet->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);

復(fù)制

設(shè)置默認列寬為12:

$spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(12);

復(fù)制

行高

設(shè)置第10行行高為100pt:

$spreadsheet->getActiveSheet()->getRowDimension('10')->setRowHeight(100);

復(fù)制

設(shè)置默認行高:

$spreadsheet->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);

復(fù)制

對齊

將A1單元格設(shè)置為水平居中對齊:

$styleArray = ['alignment' => ['horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,], ]; $worksheet->getStyle('A1')->applyFromArray($styleArray);

復(fù)制

合并

將A18到E22合并為一個單元格:

$spreadsheet->getActiveSheet()->mergeCells('A18:E22');

復(fù)制

拆分

將合并后的單元格拆分:

$spreadsheet->getActiveSheet()->unmergeCells('A18:E22');

復(fù)制

邊框

將B2至G8的區(qū)域添加紅色邊框:

$styleArray = ['borders' => ['outline' => ['borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,'color' => ['argb' => 'FFFF0000'],],], ]; $worksheet->getStyle('B2:G8')->applyFromArray($styleArray);

復(fù)制

工作表標題

設(shè)置當前工作表標題:

$spreadsheet->getActiveSheet()->setTitle('Hello');

復(fù)制

日期時間

設(shè)置日期格式:

$spreadsheet->getActiveSheet()->setCellValue('D1', '2018-06-15');$spreadsheet->getActiveSheet()->getStyle('D1')->getNumberFormat()->setFormatCode(\PhpOffice\PhpSpreadsheet\Style\NumberFormat::FORMAT_DATE_YYYYMMDD2);

復(fù)制

換行

使用\n進行單元格內(nèi)換行,相當于(ALT+"Enter"):

$spreadsheet->getActiveSheet()->getCell('A4')->setValue("hello\nworld"); $spreadsheet->getActiveSheet()->getStyle('A4')->getAlignment()->setWrapText(true)

復(fù)制

超鏈接

將單元格設(shè)置為超鏈接形式:

$spreadsheet->getActiveSheet()->setCellValue('E6', 'www.helloweba.net'); $spreadsheet->getActiveSheet()->getCell('E6')->getHyperlink()->setUrl('https://www.helloweba.net');

復(fù)制

使用函數(shù)

使用SUM計算B5到C5之間單元格的總和。其他函數(shù)同理:最大數(shù)(MAX),最小數(shù)(MIN),平均值(AVERAGE):

$spreadsheet->getActiveSheet()->setCellValue('B7', '=SUM(B5:C5)');

復(fù)制

設(shè)置文檔屬性

可以設(shè)置Excel文檔屬性:

$spreadsheet->getProperties()->setCreator("Helloweba") //作者->setLastModifiedBy("Yuegg") //最后修改者->setTitle("Office 2007 XLSX Test Document") //標題->setSubject("Office 2007 XLSX Test Document") //副標題->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") //描述->setKeywords("office 2007 openxml php") //關(guān)鍵字->setCategory("Test result file"); //分類

復(fù)制

此外,除了提供豐富的Excel文件處理接口外,PhpSpreadshee還提供了CSV,PDF,HTML以及XML等文件處理接口。

總結(jié)

以上是生活随笔為你收集整理的PhpOffice/PhpSpreadsheet读取和写入Excel的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。