PHP導(dǎo)入導(dǎo)出Excel方法
原作者:冰山上的播客看到這篇文章的時(shí)候,很是驚訝原作者的耐心,雖然我們?cè)谄綍r(shí)用的也有一些,但沒(méi)有作者列出來(lái)的全,寫(xiě)excel的時(shí)候,我用過(guò)pear的庫(kù),也用過(guò)pack壓包的頭,同樣那些利用smarty等作的簡(jiǎn)單替換xml的也用過(guò),csv的就更不用談了。呵呵。(COM方式不講了,這種可讀的太多了,我也寫(xiě)過(guò)利用wps等進(jìn)行word等的生成之類的文章 )但是在讀的時(shí)候,只用過(guò)一種,具體是什么忘了,要回去翻代碼了。因?yàn)椴捎玫氖悄脕?lái)主義,記不住。原文地址:http://xinsync.xju.edu.cn/index.php/archives/3858原文內(nèi)容:
最近因項(xiàng)目需要,需要開(kāi)發(fā)一個(gè)模塊,把系統(tǒng)中的一些數(shù)據(jù)導(dǎo)出成Excel,修改后再導(dǎo)回系統(tǒng)。就趁機(jī)對(duì)這個(gè)研究了一番,下面進(jìn)行一些總結(jié)。基本上導(dǎo)出的文件分為兩種:1:類Excel格式,這個(gè)其實(shí)不是傳統(tǒng)意義上的Excel文件,只是因?yàn)镋xcel的兼容能力強(qiáng),能夠正確打開(kāi)而已。修改這種文件后再保存,通常會(huì)提示你是否要轉(zhuǎn)換成Excel文件。優(yōu)點(diǎn):簡(jiǎn)單。缺點(diǎn):難以生成格式,如果用來(lái)導(dǎo)入需要自己分別編寫(xiě)相應(yīng)的程序。2:Excel格式,與類Excel相對(duì)應(yīng),這種方法生成的文件更接近于真正的Excel格式。
如果導(dǎo)出中文時(shí)出現(xiàn)亂碼,可以嘗試將字符串轉(zhuǎn)換成gb2312,例如下面就把$yourStr從utf-8轉(zhuǎn)換成了gb2312:$yourStr = mb_convert_encoding(”gb2312″, “UTF-8″, $yourStr);
下面詳細(xì)列舉幾種方法。一、PHP導(dǎo)出Excel
1:第一推薦無(wú)比風(fēng)騷的PHPExcel,官方網(wǎng)站: http://www.codeplex.com/PHPExcel導(dǎo)入導(dǎo)出都成,可以導(dǎo)出office2007格式,同時(shí)兼容2003。下載下來(lái)的包中有文檔和例子,大家可以自行研究。抄段例子出來(lái):
PHP代碼<?php/**; * PHPExcel; *; * Copyright (C) 2006 - 2007 PHPExcel; *; * This library is free software; you can redistribute it and/or; * modify it under the terms of the GNU Lesser General Public; * License as published by the Free Software Foundation; either; * version 2.1 of the License, or (at your option) any later version.; *; * This library is distributed in the hope that it will be useful,; * but WITHOUT ANY WARRANTY; without even the implied warranty of; * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.; See the GNU; * Lesser General Public License for more details.; *; * You should have received a copy of the GNU Lesser General Public; * License along with this library; if not, write to the Free Software; * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA; 02110-1301; USA; *; * @categoryPHPExcel; * @package;PHPExcel; * @copyright; Copyright (c) 2006 - 2007 PHPExcel ( http://www.codeplex.com/PHPExcel); * @license;http://www.gnu.org/licenses/lgpl.txt LGPL; * @version;1.5.0, 2007-10-23; */ /** Error reporting */error_reporting(E_ALL); /** Include path **/set_include_path(get_include_path() . PATH_SEPARATOR . ‘../Classes/’); /** PHPExcel */include ‘PHPExcel.php’; /** PHPExcel_Writer_Excel2007 */include ‘PHPExcel/Writer/Excel2007.php’; // Create new PHPExcel objectecho date(’H:i:s’) . ” Create new PHPExcel objectn”;$objPHPExcel = new PHPExcel(); // Set propertiesecho date(’H:i:s’) . ” Set propertiesn”;$objPHPExcel->getProperties()->setCreator(”Maarten Balliauw”);$objPHPExcel->getProperties()->setLastModifiedBy(”Maarten Balliauw”);$objPHPExcel->getProperties()->setTitle(”O(jiān)ffice 2007 XLSX Test Document”);$objPHPExcel->getProperties()->setSubject(”O(jiān)ffice 2007 XLSX Test Document”);$objPHPExcel->getProperties()->setDescrīption(”Test document for Office 2007 XLSX, generated using PHP classes.”);$objPHPExcel->getProperties()->setKeywords(”office 2007 openxml php”);$objPHPExcel->getProperties()->setCategory(”Test result file”); // Add some dataecho date(’H:i:s’) . ” Add some datan”;$objPHPExcel->setActiveSheetIndex(0);$objPHPExcel->getActiveSheet()->setCellValue(’A1′, ‘Hello’);$objPHPExcel->getActiveSheet()->setCellValue(’B2′, ‘world!’);$objPHPExcel->getActiveSheet()->setCellValue(’C1′, ‘Hello’);$objPHPExcel->getActiveSheet()->setCellValue(’D2′, ‘world!’); // Rename sheetecho date(’H:i:s’) . ” Rename sheetn”;$objPHPExcel->getActiveSheet()->setTitle(’Simple’); // Set active sheet index to the first sheet, so Excel opens this as the first sheet$objPHPExcel->setActiveSheetIndex(0); // Save Excel 2007 fileecho date(’H:i:s’) . ” Write to Excel2007 formatn”;$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);$objWriter->save(str_replace(’.php’, ‘.xlsx’, __FILE__)); // Echo doneecho date(’H:i:s’) . ” Done writing file.rn”;
2、使用pear的Spreadsheet_Excel_Writer類下載地址: http://pear.php.net/package/Spreadsheet_Excel_Writer此類依賴于OLE,下載地址:http://pear.php.net/package/OLE需要注意的是導(dǎo)出的Excel文件格式比較老,修改后保存會(huì)提示是否轉(zhuǎn)換成更新的格式。不過(guò)可以設(shè)定格式,很強(qiáng)大。
PHP代碼<?phprequire_once ‘Spreadsheet/Excel/Writer.php’; // Creating a workbook$workbook = new Spreadsheet_Excel_Writer(); // sending HTTP headers$workbook->send(’test.xls’); // Creating a worksheet$worksheet =& $workbook->addWorksheet(’My first worksheet’); // The actual data$worksheet->write(0, 0, ‘Name’);$worksheet->write(0, 1, ‘Age’);$worksheet->write(1, 0, ‘John Smith’);$worksheet->write(1, 1, 30);$worksheet->write(2, 0, ‘Johann Schmidt’);$worksheet->write(2, 1, 31);$worksheet->write(3, 0, ‘Juan Herrera’);$worksheet->write(3, 1, 32); // Let’s send the file$workbook->close();?>
3:利用smarty,生成符合Excel規(guī)范的XML或HTML文件支持格式,非常完美的導(dǎo)出方案。不過(guò)導(dǎo)出來(lái)的的本質(zhì)上還是XML文件,如果用來(lái)導(dǎo)入就需要另外處理了。詳細(xì)內(nèi)容請(qǐng)見(jiàn)rardge大俠的帖子:http://bbs.chinaunix.net/viewthread.php?tid=745757
需要注意的是如果導(dǎo)出的表格行數(shù)不確定時(shí),最好在模板中把”ss:ExpandedColumnCount=”5″ ss:ExpandedRowCount=”21″”之類的東西刪掉。
4、利用pack函數(shù)打印出模擬Excel格式的斷句符號(hào),這種更接近于Excel標(biāo)準(zhǔn)格式,用office2003修改后保存,還不會(huì)彈出提示,推薦用這種方法。缺點(diǎn)是無(wú)格式。
PHP代碼<?php// Send Headerheader(”P(pán)ragma: public”);header(”Expires: 0″);header(”Cache-Control: must-revalidate, post-check=0, pre-check=0″);header(”Content-Type: application/force-download”);header(”Content-Type: application/octet-stream”);header(”Content-Type: application/download”);;header(”Content-Disposition: attachment;filename=test.xls “);header(”Content-Transfer-Encoding: binary “);// XLS Data Cell xlsBOF();xlsWriteLabel(1,0,”My excel line one”);xlsWriteLabel(2,0,”My excel line two : “);xlsWriteLabel(2,1,”Hello everybody”); xlsEOF(); function xlsBOF() {echo pack(”ssssss”, 0×809, 0×8, 0×0, 0×10, 0×0, 0×0);return;}function xlsEOF() {echo pack(”ss”, 0×0A, 0×00);return;}function xlsWriteNumber($Row, $Col, $Value) {echo pack(”sssss”, 0×203, 14, $Row, $Col, 0×0);echo pack(”d”, $Value);return;}function xlsWriteLabel($Row, $Col, $Value ) {$L = strlen($Value);echo pack(”ssssss”, 0×204, 8 + $L, $Row, $Col, 0×0, $L);echo $Value;return;}?>不過(guò)筆者在64位linux系統(tǒng)中使用時(shí)失敗了,斷句符號(hào)全部變成了亂碼。 5、使用制表符、換行符的方法制表符”t”用戶分割同一行中的列,換行符”tn”可以開(kāi)啟下一行。<?phpheader(”Content-Type: application/vnd.ms-execl”);header(”Content-Disposition: attachment; filename=myExcel.xls”);header(”P(pán)ragma: no-cache”);header(”Expires: 0″);/*first line*/echo “hello”.”t”;echo “world”.”t”;echo “tn”; /*start of second line*/echo “this is second line”.”t”;echo “Hi,pretty girl”.”t”;echo “tn”;?>
6、使用com如果你的PHP可以開(kāi)啟com模塊,就可以用它來(lái)導(dǎo)出Excel文件
PHP代碼<?PHP$filename = “c:/spreadhseet/test.xls”;$sheet1 = 1;$sheet2 = “sheet2″;$excel_app = new COM(”Excel.application”) or Die (”Did not connect”);print “Application name: {$excel_app->Application->value}n” ;print “Loaded version: {$excel_app->Application->version}n”;$Workbook = $excel_app->Workbooks->Open(”$filename”) or Die(”Did not open $filename $Workbook”);$Worksheet = $Workbook->Worksheets($sheet1);$Worksheet->activate;$excel_cell = $Worksheet->Range(”C4″);$excel_cell->activate;$excel_result = $excel_cell->value;print “$excel_resultn”;$Worksheet = $Workbook->Worksheets($sheet2);$Worksheet->activate;$excel_cell = $Worksheet->Range(”C4″);$excel_cell->activate;$excel_result = $excel_cell->value;print “$excel_resultn”;#To close all instances of excel:$Workbook->Close;unset($Worksheet);unset($Workbook);$excel_app->Workbooks->Close();$excel_app->Quit();unset($excel_app);?>
一個(gè)更好的例子: http://blog.chinaunix.net/u/16928/showart_387171.html
一、PHP導(dǎo)入Excel
1:還是用PHPExcel,官方網(wǎng)站: http://www.codeplex.com/PHPExcel。
2:使用PHP-ExcelReader,下載地址: http://sourceforge.net/projects/phpexcelreader舉例:
PHP代碼<?phprequire_once ‘Excel/reader.php’; // ExcelFile($filename, $encoding);$data = new Spreadsheet_Excel_Reader(); // Set output Encoding.$data->setOutputEncoding(’utf8′); $data->read(’ jxlrwtest.xls’); error_reporting(E_ALL ^ E_NOTICE); for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {for ($j = 1; $j <= $data->sheets[0]['numCols']; $j++) {echo “”'.$data->sheets[0]['cells'][$i][$j].””,”;}echo “n”;} ?>
----------本站采用創(chuàng)作共享版權(quán)協(xié)議, 要求署名、非商業(yè)和保持一致. 本站歡迎任何非商業(yè)應(yīng)用的轉(zhuǎn)載, 但須注明出自' 膘叔簡(jiǎn)單人生', 保留原始鏈接, 此外還必須標(biāo)注原文標(biāo)題和鏈接.