Linux下將excel資料匯入到mssql資料庫中的方法

來源:互聯網
上載者:User

先清理一下思路先,~~
首先:需要把檔案上傳到伺服器上
然後:讀取excel資料列顯示出來
然後:讓使用者選擇欄位的對應關係
然後:提交資料,讀取欄位的對應關係
最後:大量匯入資料,刪除臨時檔案
一共是以上五步驟!我們一步步分析~~~
第一步:下載附件中的phpexcelparser4.rar ,這個檔案是上傳excel盜伺服器上並以web形式展示出來的!這個一般沒有問題的!問題是程式的做法是把表存為暫存資料表而沒有真正儲存下來,所以首先要更改程式碼為 複製代碼 代碼如下:if (trim($_POST["cmd"])=="upload")
{

$err_corr = "Unsupported format or file corrupted";

$excel_file_size;
$excel_file = $_FILES['excel_file'];
$uploadservername=$UploadAbsPath."tmpexcel/".$_FILES['excel_file']['name'];
echo($uploadservername);
if (!is_writeable($UploadAbsPath."tmpexcel/"))
{
echo "目錄不可寫!"; exit;
}
else
{
echo "目錄可寫!";
}
if (move_uploaded_file($_FILES['excel_file']['tmp_name'], $uploadservername))
{
echo("上傳成功");
}
else
{
echo("上傳失敗");
}
$excel_file=$uploadservername;
//if( $excel_file )
// $excel_file = $_FILES['excel_file']['tmp_name'];

if( $excel_file == '' ) fatal("No file uploaded");

$exc = new ExcelFileParser("debug.log", ABC_NO_LOG);//ABC_NO_LOG ABC_VAR_DUMP);
//echo($excel_file."|");
$style = $_POST['style'];
if( $style == 'old' )
{
$fh = @fopen ($excel_file,'rb');
if( !$fh ) fatal("No file uploaded");
if( filesize($excel_file)==0 ) fatal("No file uploaded");
$fc = fread( $fh, filesize($excel_file) );
@fclose($fh);
if( strlen($fc) < filesize($excel_file) )
fatal("Cannot read file");
$time_start = getmicrotime();
$res = $exc->ParseFromString($fc);
$time_end = getmicrotime();
}
elseif( $style == 'segment' )
{
$time_start = getmicrotime();
$res = $exc->ParseFromFile($excel_file);
$time_end = getmicrotime();
}

switch ($res) {
case 0: break;
case 1: fatal("Can't open file");
case 2: fatal("File too small to be an Excel file");
case 3: fatal("Error reading file header");
case 4: fatal("Error reading file");
case 5: fatal("This is not an Excel file or file stored in Excel < 5.0");
case 6: fatal("File corrupted");
case 7: fatal("No Excel data found in file");
case 8: fatal("Unsupported file version");

default:
fatal("Unknown error");
}

/*
print '<pre>';
print_r( $exc );
print '</pre>';
exit;
*/

show_time();

echo <<<LEG
<b>Legend:</b><br><br>
<form name='doform' action='' method='post'>
<input type='hidden' name='action' value='do'>
<input type='hidden' name='excel_file' value=$excel_file>
<input type='hidden' name='style' value=$style>
<table border=1 cellspacing=0 cellpadding=0>
<tr><td>Data type</td><td>Description</td></tr>
<tr><td class=empty> </td><td class=index>An empty cell</td></tr>
<tr><td class=dt_string>ABCabc</td><td class=index>String</td></tr>
<tr><td class=dt_int>12345</td><td class=index>Integer</td></tr>
<tr><td class=dt_float>123.45</td><td class=index>Float</td></tr>
<tr><td class=dt_date>123.45</td><td class=index>Date</td></tr>
<table>
<br><br>

LEG;
/*
print "<pre>";
print_r ($exc->worksheet);
print_r($exc->sst);
print "</pre>";
*/
for( $ws_num=0; $ws_num<count($exc->worksheet['name']); $ws_num++ )
{
print "<b>Worksheet: \"";
if( $exc->worksheet['unicode'][$ws_num] ) {
print uc2html($exc->worksheet['name'][$ws_num]);
} else
print $exc->worksheet['name'][$ws_num];

print "\"</b>";
$ws = $exc->worksheet['data'][$ws_num];

if( is_array($ws) &&
isset($ws['max_row']) && isset($ws['max_col']) ) {
echo "\n<br><br><table border=1 cellspacing=0 cellpadding=2>\n";

print "<tr><td> </td>\n";
for( $j=0; $j<=$ws['max_col']; $j++ ) {
print "<td class=index> ";
if( $j>25 ) print chr((int)($j/26)+64);
//這裡要顯示一個下拉式清單來顯示資料
//注意是迴圈資料<br />
echo("\n<select name='".$j."'>");
echo("\n<option value='0'>不選擇</option>");
echo("\n<option value='fkhxm'>客戶姓名</option>");
echo("\n<option value='fsfzh'>社會安全號碼</option>");
echo("\n<option value='fyddh'>行動電話</option>");
echo("\n<option value='ftxdz'>通訊地址</option>");
echo("\n<option value='femail'>Email</option>");
echo("\n<option value='flxdh'>聯絡電話</option>");
echo("\n<option value='fkhah'>客戶愛好</option>");
echo("\n<option value='fbzxx'>備忘資訊</option>");
echo("</select>");
print "</td>";
}

print "<tr><td> </td>\n";
for( $j=0; $j<=$ws['max_col']; $j++ ) {
print "<td class=index> ";
if( $j>25 ) print chr((int)($j/26)+64);
print chr(($j % 26) + 65)." 列名</td>";
}

//表頭輸出完畢
if ($ws['max_row']>9)
{
$shownum=9;
}
else
{
$shownum=$ws['max_row'];//只輸出前10條資料
}
for( $i=0; $i<=$shownum; $i++ ) {
print "<tr><td class=index>".($i+1)."</td>\n";
if(isset($ws['cell'][$i]) && is_array($ws['cell'][$i]) ) {
for( $j=0; $j<=$ws['max_col']; $j++ ) {

if( ( is_array($ws['cell'][$i]) ) &&
( isset($ws['cell'][$i][$j]) )
){

// print cell data
print "<td class=\"";
$data = $ws['cell'][$i][$j];

$font = $ws['cell'][$i][$j]['font'];
$style = " style ='".ExcelFont::ExcelToCSS($exc->fonts[$font])."'";

switch ($data['type']) {
// string
case 0:
print "dt_string\"".$style.">";
$ind = $data['data'];
if( $exc->sst['unicode'][$ind] ) {
$s = uc2html($exc->sst['data'][$ind]);
} else
$s = $exc->sst['data'][$ind];
if( strlen(trim($s))==0 )
print " ";
else
print $s;
break;
// integer number
case 1:
print "dt_int\"".$style."> ";
print $data['data'];
break;
// float number
case 2:
print "dt_float\"".$style."> ";
echo $data['data'];
break;
// date
case 3:
print "dt_date\"".$style."> ";

$ret = $data[data];//str_replace ( " 00:00:00", "", gmdate("d-m-Y H:i:s",$exc->xls2tstamp($data[data])) );
echo ( $ret );
break;
default:
print "dt_unknown\"".$style."> ";
break;
}
print "</td>\n";
} else {
print "<td class=empty> </td>\n";
}
}
} else {
// print an empty row
for( $j=0; $j<=$ws['max_col']; $j++ )
print "<td class=empty> </td>";
print "\n";
}
print "</tr>\n";
}

echo "</table><br>\n";
} else {
// emtpty worksheet
print "<b> - empty</b><br>\n";
}
print "<br>";

}
echo("<input type='submit' name='Submit' value='轉換' />");
echo("</form>");
/* print "Formats<br>";
foreach($exc->format as $value) {
printf("( %x )",array_search($value,$exc->format));
print htmlentities($value,ENT_QUOTES);
print "<br>";
}

print "XFs<br>";
for( $i=0;$i<count($exc->xf['format']);$i++) {
printf ("(%x)",$i);
printf (" format (%x) font (%x)",$exc->xf['format'][$i],$exc->xf['font'][$i]);

print "<br>";
}
*/
}

運行效果如下:

第二步是要讀取資料出來,代碼如下: 複製代碼 代碼如下:if ($_POST["action"]=="do")
{
//處理資料
//先讀取表頭記錄
$excel_file=$_POST["excel_file"];
$fh = @fopen ($excel_file,'rb');
$fc = fread( $fh, filesize($excel_file) );
@fclose($fh);
//echo("執行".$excel_file);
$exc = new ExcelFileParser("debug.log", ABC_NO_LOG);//ABC_NO_LOG ABC_VAR_DUMP);
//echo($excel_file."|");
$style = $_POST['style'];
if( $style == 'old' )
{
$fh = @fopen ($excel_file,'rb');
if( !$fh ) fatal("No file uploaded");
if( filesize($excel_file)==0 ) fatal("No file uploaded");
$fc = fread( $fh, filesize($excel_file) );
@fclose($fh);
if( strlen($fc) < filesize($excel_file) )
fatal("Cannot read file");
$time_start = getmicrotime();
$res = $exc->ParseFromString($fc);
$time_end = getmicrotime();
}
elseif( $style == 'segment' )
{
$time_start = getmicrotime();
$res = $exc->ParseFromFile($excel_file);
$time_end = getmicrotime();
}

switch ($res) {
case 0: break;
case 1: fatal("Can't open file");
case 2: fatal("File too small to be an Excel file");
case 3: fatal("Error reading file header");
case 4: fatal("Error reading file");
case 5: fatal("This is not an Excel file or file stored in Excel < 5.0");
case 6: fatal("File corrupted");
case 7: fatal("No Excel data found in file");
case 8: fatal("Unsupported file version");

default:
fatal("Unknown error");
}
//以及讀取完畢,如果沒有錯誤的話就可以迴圈往MSSQL中增加資料了!
for( $ws_num=0; $ws_num<count($exc->worksheet['name']); $ws_num++ )
{
// print "<b>Worksheet: \"";
// if( $exc->worksheet['unicode'][$ws_num] ) {
// print uc2html($exc->worksheet['name'][$ws_num]);
// } else
// print $exc->worksheet['name'][$ws_num];
//
// print "\"</b>";
$ws = $exc->worksheet['data'][$ws_num];
//
//
// print "<tr><td> </td>\n";
$fkhxmnum=0;
$fsfzhnum=0;
$fyddhnum=0;
$ftxdznum=0;
$femailnum=0;
$flxdhnum=0;
$fkhahnum=0;
$fbzxxnum=0;
for( $j=0; $j<=$ws['max_col']; $j++ ) {
//print "<td class=index> ";
//if( $j>25 ) print chr((int)($j/26)+64);
//先讀取列名

$tmpcolum=trim($_POST["$j"]);
//echo($tmpcolum."|");
if ($tmpcolum=="fkhxm") $fkhxmnum=$j;
if ($tmpcolum=="fsfzh") $fsfzhnum=$j;
if ($tmpcolum=="fyddh") $fyddhnum=$j;
if ($tmpcolum=="ftxdz") $ftxdznum=$j;
if ($tmpcolum=="femail") $femailnum=$j;
if ($tmpcolum=="flxdh") $flxdhnum=$j;
if ($tmpcolum=="fkhah") $fkhahnum=$j;
if ($tmpcolum=="fbzxx") $fbzxxnum=$j;
}
for( $i=0; $i<=$ws['max_row']; $i++ ) {
//$fkhxm=
//echo($fkhxmnum.$fsfzhnum.$fyddhnum.$ftxdznum.$femailnum.$flxdhnum.$fkhahnum.$fbzxxnum);
//print "<tr><td class=index>".($i+1)."</td>\n";
if(isset($ws['cell'][$i]) && is_array($ws['cell'][$i]) ) {
if ($fkhxmnum!=0&&$ftxdznum!=0&&($fyddhnum!=0||$flxdhnum!=0))//請在這裡指定必須的不為空白的欄位
{
$sql="insert into k_qlkhxx(fkhxm,fsfzh,fyddh,ftxdz,femail,flxdh,$fkhah,fbzxx,fglry,fglryxm,fdjry,ffzdm) values('".uc2html($exc->sst['data'][$ws['cell'][$i][$fkhxmnum]['data']])."','".$exc->sst['data'][$ws['cell'][$i][$fsfzhnum]['data']]."','".$exc->sst['data'][$ws['cell'][$i][$fyddhnum]['data']]."','".uc2html($exc->sst['data'][$ws['cell'][$i][$ftxdznum]['data']])."','".uc2html($exc->sst['data'][$ws['cell'][$i][$femailnum]['data']])."','".$exc->sst['data'][$ws['cell'][$i][$flxdhnum]['data']]."','".uc2html($exc->sst['data'][$ws['cell'][$i][$fkhahnum]['data']])."','".uc2html($exc->sst['data'][$ws['cell'][$i][$fbzxxnum]['data']])."','".$_SESSION["uyhmc"]."','".$_SESSION["uyhxm"]."','".$_SESSION["uyhmc"]."','".$_SESSION["ubm"]."')";
echo($sql."<br>");
}
//$conn->Query($sql);
}
}
}
//匯入完成刪除檔案
unlink($filename);

}

你注意沒有,我把執行的那一行注釋掉的,只要去掉注釋就可以正確執行了!
所用到的代碼打包下載http://xiazai.jb51.net/201002/yuanma/php_excel_mysql.rar

相關文章

聯繫我們

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