PHP匯入匯出Excel方法小結

來源:互聯網
上載者:User

最近因項目需要,需要開發一個模組,把系統中的一些資料匯出成Excel,修改後再導回系統。就趁機對這個研究了一番,下面進行一些總結。
基本上匯出的檔案分為兩種:
1:類Excel格式,這個其實不是傳統意義上的Excel檔案,只是因為Excel的相容能力強,能夠正確開啟而已。修改這種檔案後再儲存,通常會提示你是否要轉換成Excel檔案。
優點:簡單。
缺點:難以產生格式,如果用來匯入需要自己分別編寫相應的程式。
2:Excel格式,與類Excel相對應,這種方法產生的檔案更接近於真正的Excel格式。

如果匯出中文時出現亂碼,可以嘗試將字串轉換成gb2312,例如下面就把$yourStr從utf-8轉換成了gb2312:
$yourStr = mb_convert_encoding("gb2312", "UTF-8", $yourStr);

下面詳細列舉幾種方法。
一、PHP匯出Excel

1:第一推薦無比風騷的PHPExcel,官方網站: http://www.codeplex.com/PHPExcel
匯入匯出都成,可以匯出office2007格式,同時相容2003。
下載下來的包中有文檔和例子,大家可以自行研究。
抄段例子出來:
<?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
 *
 * @category   PHPExcel
 * @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 object
echo date('H:i:s') . " Create new PHPExcel object\n";
$objPHPExcel = new PHPExcel();

// Set properties
echo date('H:i:s') . " Set properties\n";
$objPHPExcel->getProperties()->setCreator("Maarten Balliauw");
$objPHPExcel->getProperties()->setLastModifiedBy("Maarten Balliauw");
$objPHPExcel->getProperties()->setTitle("Office 2007 XLSX Test Document");
$objPHPExcel->getProperties()->setSubject("Office 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 data
echo date('H:i:s') . " Add some data\n";
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello');
$objPHPExcel->getActiveSheet()->setCellValue('B2', 'world!');
$objPHPExcel->getActiveSheet()->setCellValue('C1', 'Hello');
$objPHPExcel->getActiveSheet()->setCellValue('D2', 'world!');

// Rename sheet
echo date('H:i:s') . " Rename sheet\n";
$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 file
echo date('H:i:s') . " Write to Excel2007 format\n";
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save(str_replace('.php', '.xlsx', __FILE__));

// Echo done
echo date('H:i:s') . " Done writing file.\r\n";

2、使用pear的Spreadsheet_Excel_Writer類
: http://pear.php.net/package/Spreadsheet_Excel_Writer
此類依賴於OLE,:http://pear.php.net/package/OLE
需要注意的是匯出的Excel檔案格式比較老,修改後儲存會提示是否轉換成更新的格式。
不過可以設定格式,很強大。
<?php
require_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規範的或檔案HTMLXML
支援格式,非常完美的匯出方案。不過匯出來的的本質上還是XML檔案,如果用來匯入就需要另外處理了。
詳細內容請見rardge大俠的文章:http://bbs.chinaunix.net/viewthread.php?tid=745757

需要注意的是如果匯出的表格行數不確定時,最好在模板中把"ss:ExpandedColumnCount="5" ss:ExpandedRowCount="21""之類的東西刪掉。

4、利用pack函數列印出類比Excel格式的斷句符號,這種更接近於Excel標準格式,用office2003修改後儲存,還不會彈出提示,推薦用這種方法。
缺點是無格式。
<?php
// Send Header
header("Pragma: 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", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
    return;
}
function xlsEOF() {
    echo pack("ss", 0x0A, 0x00);
    return;
}
function xlsWriteNumber($Row, $Col, $Value) {
    echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
    echo pack("d", $Value);
    return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
    $L = strlen($Value);
    echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
    echo $Value;
    return;
}
?>
不過筆者在64位linux系統中使用時失敗了,斷句符號全部變成了亂碼。

5、使用定位字元、分行符號的方法
定位字元"\t"使用者分割同一行中的列,分行符號"\t\n"可以開啟下一行。
<?php
header("Content-Type: application/vnd.ms-execl");
header("Content-Disposition: attachment; filename=myExcel.xls");
header("Pragma: no-cache");
header("Expires: 0");
/*first line*/
echo "hello"."\t";
echo "world"."\t";
echo "\t\n";

/*start of second line*/
echo "this is second line"."\t";
echo "Hi,pretty girl"."\t";
echo "\t\n";
?>

6、使用com
如果你的PHP可以開啟com模組,就可以用它來匯出Excel檔案
<?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_result\n";
$Worksheet = $Workbook->Worksheets($sheet2);
$Worksheet->activate;
$excel_cell = $Worksheet->Range("C4");
$excel_cell->activate;
$excel_result = $excel_cell->value;
print "$excel_result\n";
#To close all instances of excel:
$Workbook->Close;
unset($Worksheet);
unset($Workbook);
$excel_app->Workbooks->Close();
$excel_app->Quit();
unset($excel_app);
?>
一個更好的例子: http://blog.chinaunix.net/u/16928/showart_387171.html

一、PHP匯入Excel

1:還是用PHPExcel,官方網站: http://www.codeplex.com/PHPExcel。

2:使用PHP-ExcelReader,: http://sourceforge.net/projects/phpexcelreader
舉例:
<?php
require_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";
}

?>

本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/binger819623/archive/2009/06/22/4289544.aspx

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.