使用PHP匯入Excel和匯出資料為Excel檔案

來源:互聯網
上載者:User
有時需要將Excel表格的資料匯入到mysql資料庫中,我們使用PHP的一個開源項目PHP-ExcelReader可以輕鬆實現Excel的匯入。

1、匯入XLS

PHP-ExcelReader這是一個開源的項目,主要是來解析excel的檔案,您可以到 http://sourceforge.net/projects/phpexcelreader擷取最新版的源碼。下載之後解壓,主要用到excel檔案夾裡面的兩個檔案reader.php和oleread.inc。

匯入Xls處理流程:選擇xls檔案->上傳xls檔案到伺服器->通過PHP-ExcelReader解析excel->批量入庫。

include_once("excel/reader.php"); //引入PHP-ExcelReader$tmp = $_FILES['file']['tmp_name'];if (empty ($tmp)) {echo '請選擇要匯入的Excel檔案!';exit;}$save_path = "xls/";$file_name = $save_path.date('Ymdhis') . ".xls"; //上傳後的檔案儲存路徑和名稱if (copy($tmp, $file_name)) {$xls = new Spreadsheet_Excel_Reader();$xls->setOutputEncoding('utf-8');  //設定編碼$xls->read($file_name);  //解析檔案for ($i=2; $i<=$xls->sheets[0]['numRows']; $i++) {$name = $xls->sheets[0]['cells'][$i][0];$sex = $xls->sheets[0]['cells'][$i][1];$age = $xls->sheets[0]['cells'][$i][2];$data_values .= "('$name','$sex','$age'),";}$data_values = substr($data_values,0,-1); //去掉最後一個逗號$query = mysql_query("insert into student (name,sex,age) values $data_values");//批量插入資料表中if($query){echo '匯入成功!';}else{echo '匯入失敗!';}}

PHP-ExcelReader讀取上傳的excel檔案後,返回一個數組,裡麵包含了表格的所有資訊,你可以迴圈擷取需要的資訊。

2、匯出XLS

匯出XLS流程:讀取學生資訊表->迴圈記錄構建定位字元分隔的欄位資訊->設定header資訊->匯出檔案(下載)到本地

$result = mysql_query("select * from student");$str = "姓名\t性別\t年齡\t\n";$str = iconv('utf-8','gb2312',$str);while($row=mysql_fetch_array($result)){    $name = iconv('utf-8','gb2312',$row['name']);    $sex = iconv('utf-8','gb2312',$row['sex']);    $str .= $name."\t".$sex."\t".$row['age']."\t\n";}$filename = date('Ymd').'.xls';exportExcel($filename,$str);

exportExcel函數用於設定header資訊。

function exportExcel($filename,$content){ header("Cache-Control: must-revalidate, post-check=0, pre-check=0");header("Content-Type: application/vnd.ms-execl");header("Content-Type: application/force-download");header("Content-Type: application/download");    header("Content-Disposition: attachment; filename=".$filename);    header("Content-Transfer-Encoding: binary");    header("Pragma: no-cache");    header("Expires: 0");    echo $content;}

此外,關於匯入和匯出Excel,還可以使用PHPExcel,這個非常強大,大家有空可以去研究,官方網站: http://www.codeplex.com/PHPExcel 匯入匯出都成,可以匯出office2007格式,同時相容2003
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.