国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法

Original 2017-01-21 15:41:24 472
abstract:本文實例講述了PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:一.導(dǎo)入導(dǎo)入需要使用能讀取Excel的組件,網(wǎng)上也有比較好的組件,這里分享我使用的:下載  提取碼:vxyn。(注意兩個文件有引用關(guān)系)<?php //傳入要導(dǎo)入的Excel的文件名 function import_to_DB($filename)&nbs

本文實例講述了PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法。分享給大家供大家參考。具體實現(xiàn)方法如下:

一.導(dǎo)入

導(dǎo)入需要使用能讀取Excel的組件,網(wǎng)上也有比較好的組件,這里分享我使用的:下載  提取碼:vxyn。(注意兩個文件有引用關(guān)系)

<?php
//傳入要導(dǎo)入的Excel的文件名
function import_to_DB($filename) {
  require_once'reader.php';
  $data = new Spreadsheet_Excel_Reader();
  //創(chuàng)建讀取Excel的對象
  $data->setOutputEncoding('utf-8');
  //設(shè)置讀取Excel內(nèi)容后輸出的字符編碼
  $data->read("data/Excel/{$filename}.xls");
  $db = mysql_connect('localhost', '用戶名', '密碼') or die("Could not connect to database.");
  //連接數(shù)據(jù)庫 
  mysql_query("set names 'uft8'");
  //輸出中文 
  mysql_SELECT_db('數(shù)據(jù)庫名');
  //選擇數(shù)據(jù)庫 
  error_reporting(E_ALL ^ E_NOTICE);
  for ($i = 1; $i <= $data->sheets[0]['numRows']; $i++) {
    echo $data->sheets[0]['cells'][$i][列數(shù)];
    //這里可以把每一行相應(yīng)列的值插到數(shù)據(jù)庫中,如:
    /*
    $sql="INSERT "表名" values(對應(yīng)項...)";
    mysql_query($sql);
    可加上錯誤判斷
    */
  }
?>

總之,能夠讀出表格中每一行中的相應(yīng)列$data->sheets[0][行][列]的值,插入操作就好辦了。

二.導(dǎo)出

導(dǎo)出可以利用MIME協(xié)議輕松導(dǎo)出表格文件,不用依賴任何組件。按如下格式設(shè)置header即可導(dǎo)出Excel,同時瀏覽器進(jìn)行下載

header('Content-type: text/html; charset=utf-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8"); //application/vnd.ms-excel指定輸出Excel格式
header("Content-Disposition:filename=表格文件名.xls");
//輸出的表格名稱

完整代碼如下:

<?php
header('Content-type: text/html; charset=utf-8');
header("Content-type:application/vnd.ms-excel;charset=UTF-8");
header("Content-Disposition:filename=表格文件名.xls");
$conn = mysql_connect("localhost","root","數(shù)據(jù)庫密碼") or die("不能連接數(shù)據(jù)庫");
mysql_SELECT_db("數(shù)據(jù)庫名", $conn);
mysql_query("set names 'UTF-8'");
$sql="SELECT * from 表名 where 條件";
$result=mysql_query($sql);
echo "表頭1\t表頭2\t表頭3\n";
while($row=mysql_fetch_array($result)){
  echo $row[0]."\t".$row[1]."\t".$row[2]."\n";
}
?>

這里其實\t就是換格,\n就是換行。在一個網(wǎng)頁中設(shè)置這個php文件的鏈接,當(dāng)點擊時瀏覽器會自動把傳過來的流保存為Excel文件。

更多關(guān)于PHP將Excel導(dǎo)入數(shù)據(jù)庫及數(shù)據(jù)庫數(shù)據(jù)導(dǎo)出至Excel的方法請關(guān)注PHP中文網(wǎng)(www.miracleart.cn)其他文章! 

Release Notes

Popular Entries