TShopping

 找回密碼
 註冊
搜索
查看: 2049|回復: 3
打印 上一主題 下一主題

[分享] Linux下把excel數據導入到mysql數據庫(亂碼問題已解決)

  [複製鏈接]
跳轉到指定樓層
1#
發表於 2011-11-6 13:38:10 | 只看該作者 |只看大圖 回帖獎勵 |倒序瀏覽 |閱讀模式
 
Push to Facebook
說明:在Linux下把excel數據導入到mysql數據庫中,這實在是很搞笑的一個活動!幾乎很少有程序員研究過這個問題吧?如此變態的問題,估計我是第一個研究的!呵呵,完全是自找苦吃~~,但是今天完了這項太有挑戰性的工作!
先清理一下思路先,~~
首先:需要把文件上傳到服務器上
然後:讀取excel數據列顯示出來
然後:讓用戶選擇字段的對應關係
然後:提交數據,讀取字段的對應關係
最後:批量導入數據,刪除臨時文件
一共是以上五步驟!我們一步步分析~~~
第一步:下載附件中的phpexcelparser4.rar ,這個文件是上傳excel盜服務器上並以web形式展示出來的!這個一般沒有問題的!問題是程序的做法是把表存為臨時表而沒有真正保存下來,所以首先要更改程序代碼為



  1. //uc轉換成html
  2. function uc2html($str) {
  3.    $ret = '';
  4.    for( $i=0; $i<strlen($str)/2; $i++ ) {
  5.        $charcode = ord($str[$i*2])+256*ord($str[$i*2+1]);
  6.        // $ret .= '&#'.$charcode;
  7.        if($charcode<127)
  8.          $ret .=chr($charcode);
  9.        else
  10.            $ret .= iconv("utf-8","utf-8",u2utf8($charcode));
  11.    }
  12.        return $ret;
  13. }
  14. //html轉成utf8
  15. function u2utf8($c) {
  16. $str="";
  17. if ($c < 0x80) {
  18.   $str.=$c;
  19. } else if ($c < 0x800) {
  20.   $str.=chr(0xC0 | $c>>6);
  21.   $str.=chr(0x80 | $c & 0x3F);
  22. } else if ($c < 0x10000) {
  23.   $str.=chr(0xE0 | $c>>12);
  24.   $str.=chr(0x80 | $c>>6 & 0x3F);
  25.   $str.=chr(0x80 | $c & 0x3F);
  26. } else if ($c < 0x200000) {
  27.   $str.=chr(0xF0 | $c>>18);
  28.   $str.=chr(0x80 | $c>>12 & 0x3F);
  29.   $str.=chr(0x80 | $c>>6 & 0x3F);
  30.   $str.=chr(0x80 | $c & 0x3F);
  31. }
  32. return $str;
  33. }

  34. if (trim($_POST["cmd"])=="upload")
  35. {
  36. $err_corr = "Unsupported format or file corrupted";
  37. $excel_file_size;
  38. $excel_file = $_FILES['excel_file'];
  39. $uploadservername=$UploadAbsPath."tmpexcel/".$_FILES['excel_file']['name'];
  40. echo($uploadservername);
  41.      if (!is_writeable($UploadAbsPath."tmpexcel/"))
  42.      {
  43.      echo "目錄不可寫!"; exit;
  44.      }
  45.      else
  46.      {
  47.      echo "目錄可寫!";
  48.      }
  49. if (move_uploaded_file($_FILES['excel_file']['tmp_name'], $uploadservername))
  50. {
  51.     echo("上傳成功");
  52. }
  53. else
  54. {
  55.     echo("上傳失敗");
  56. }
  57. $excel_file=$uploadservername;
  58. //if( $excel_file )
  59. //    $excel_file = $_FILES['excel_file']['tmp_name'];


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


  61. $exc = new ExcelFileParser("debug.log", ABC_NO_LOG);//ABC_NO_LOG ABC_VAR_DUMP);
  62.     //echo($excel_file."|");
  63.    
  64. $style = $_POST['style'];
  65. if( $style == 'old' )
  66. {
  67.     $fh = @fopen ($excel_file,'rb');
  68.     if( !$fh ) fatal("No file uploaded");
  69.     if( filesize($excel_file)==0 ) fatal("No file uploaded");
  70.     $fc = fread( $fh, filesize($excel_file) );
  71.     @fclose($fh);
  72.     if( strlen($fc) < filesize($excel_file) )
  73.     fatal("Cannot read file");
  74.    
  75.     $time_start = getmicrotime();
  76.     $res = $exc->ParseFromString($fc);
  77.     $time_end = getmicrotime();
  78. }
  79. elseif( $style == 'segment' )
  80. {
  81.     $time_start = getmicrotime();
  82.     $res = $exc->ParseFromFile($excel_file);
  83.     $time_end = getmicrotime();
  84. }


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


  95.     default:
  96.     fatal("Unknown error");
  97. }


  98. /*
  99. print '<pre>';
  100. print_r( $exc );
  101. print '</pre>';
  102. exit;
  103. */


  104. show_time();


  105. echo <<<LEG
  106. <b>Legend:</b><br><br>
  107. <form name='doform' action='' method='post'>
  108. <input type='hidden' name='action' value='do'>
  109. <input type='hidden' name='excel_file' value=$excel_file>
  110. <input type='hidden' name='style' value=$style>
  111. <table border=1 cellspacing=0 cellpadding=0>
  112. <tr><td>Data type</td><td>Description</td></tr>
  113. <tr><td class=empty>&nbsp;</td><td class=index>An empty cell</td></tr>
  114. <tr><td class=dt_string>ABCabc</td><td class=index>String</td></tr>
  115. <tr><td class=dt_int>12345</td><td class=index>Integer</td></tr>
  116. <tr><td class=dt_float>123.45</td><td class=index>Float</td></tr>
  117. <tr><td class=dt_date>123.45</td><td class=index>Date</td></tr>
  118. <table>
  119. <br><br>


  120. LEG;
  121. /*
  122. print "<pre>";
  123. print_r ($exc->worksheet);
  124. print_r($exc->sst);
  125. print "</pre>";
  126. */
  127.     for( $ws_num=0; $ws_num<count($exc->worksheet['name']); $ws_num++ )
  128.     {
  129.     print "<b>Worksheet: \"";
  130.     if( $exc->worksheet['unicode'][$ws_num] ) {
  131.     print uc2html($exc->worksheet['name'][$ws_num]);
  132.     } else
  133.     print $exc->worksheet['name'][$ws_num];


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


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


  139.      print "<tr><td>&nbsp;</td>\n";
  140.      for( $j=0; $j<=$ws['max_col']; $j++ ) {
  141.     print "<td class=index>&nbsp;";
  142.     if( $j>25 ) print chr((int)($j/26)+64);
  143.     //這裡要顯示一個下拉列表來顯示數據
  144.     //注意是循環數據<br />
  145.     echo("\n<select name='".$j."'>");
  146.     echo("\n<option value='0'>不選擇</option>");
  147.    echo("\n<option value='costomernum'>客戶編號</option>");
  148.    echo("\n<option value='name'>客戶姓名</option>");
  149.    echo("\n<option value='phone1'>電話1</option>");
  150.    echo("\n<option value='phone2'>電話2</option>");
  151.    echo("\n<option value='address1'>地址1</option>");
  152.    echo("\n<option value='address2'>地址2</option>");  
  153.    echo("\n<option value='company'>公司</option>");
  154.    echo("\n<option value='levelc'>職稱</option>");   
  155.    echo("\n<option value='ps'>備註</option>");
  156.    
  157.     echo("</select>");
  158.     print "</td>";
  159.      }


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



  166. //表頭輸出完畢
  167.     if ($ws['max_row']>9)
  168.     {
  169.     $shownum=9;
  170.     }
  171.     else
  172.     {
  173.     $shownum=$ws['max_row'];//只輸出前10條數據
  174.     }
  175.      for( $i=0; $i<=$shownum; $i++ ) {
  176.      print "<tr><td class=index>".($i+1)."</td>\n";
  177.      if(isset($ws['cell'][$i]) && is_array($ws['cell'][$i]) ) {
  178.          for( $j=0; $j<=$ws['max_col']; $j++ ) {


  179.     if( ( is_array($ws['cell'][$i]) ) &&
  180.          ( isset($ws['cell'][$i][$j]) )
  181.          ){


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


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


  187.          switch ($data['type']) {
  188.     // string
  189.     case 0:
  190.         print "dt_string\"".$style.">";
  191.         $ind = $data['data'];
  192.         if( $exc->sst['unicode'][$ind] ) {
  193.         $s = uc2html($exc->sst['data'][$ind]);
  194.         } else
  195.         $s = $exc->sst['data'][$ind];
  196.         if( strlen(trim($s))==0 )
  197.         print "&nbsp;";
  198.         else
  199.         print $s;
  200.         break;
  201.     // integer number
  202.     case 1:
  203.         print "dt_int\"".$style.">&nbsp;";
  204.         print $data['data'];
  205.         break;
  206.     // float number
  207.     case 2:
  208.         print "dt_float\"".$style.">&nbsp;";
  209.         echo $data['data'];
  210.         break;
  211.     // date
  212.     case 3:
  213.         print "dt_date\"".$style.">&nbsp;";


  214.         $ret = $data[data];//str_replace ( " 00:00:00", "", gmdate("d-m-Y H:i:s",$exc->xls2tstamp($data[data])) );
  215.         echo ( $ret );
  216.         break;
  217.     default:
  218.         print "dt_unknown\"".$style."> &nbsp;";
  219.         break;
  220.          }
  221.      print "</td>\n";
  222.     } else {
  223.         print "<td class=empty>&nbsp;</td>\n";
  224.     }
  225.          }
  226.      } else {
  227.     // print an empty row
  228.     for( $j=0; $j<=$ws['max_col']; $j++ )
  229.         print "<td class=empty>&nbsp;</td>";
  230.     print "\n";
  231.      }
  232.      print "</tr>\n";
  233.      }


  234.      echo "</table><br>\n";
  235.     } else {
  236.     // emtpty worksheet
  237.     print "<b> - empty</b><br>\n";
  238.     }
  239.     print "<br>";


  240.     }
  241.     echo("<input type='submit' name='Submit' value='轉換' />");
  242.     echo("</form>");
  243. /*    print "Formats<br>";
  244.     foreach($exc->format as $value) {
  245.     printf("( %x )",array_search($value,$exc->format));
  246.     print htmlentities($value,ENT_QUOTES);
  247.     print "<br>";
  248.     }


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


  253.     print "<br>";
  254.     }
  255. */
  256. }
複製代碼

運行效果如下:
第二步是要讀取數據出來,代碼如下:

  1. if ($_POST["action"]=="do")
  2. {
  3.     //處理數據
  4.     //先讀取表頭記錄
  5.    
  6.     $excel_file=$_POST["excel_file"];
  7.     $fh = @fopen ($excel_file,'rb');
  8.     $fc = fread( $fh, filesize($excel_file) );
  9.     @fclose($fh);
  10.     //echo("執行".$excel_file);
  11.     $exc = new ExcelFileParser("debug.log", ABC_NO_LOG);//ABC_NO_LOG ABC_VAR_DUMP);
  12.     //echo($excel_file."|");
  13.    
  14. $style = $_POST['style'];
  15. if( $style == 'old' )
  16. {
  17.     $fh = @fopen ($excel_file,'rb');
  18.     if( !$fh ) fatal("No file uploaded");
  19.     if( filesize($excel_file)==0 ) fatal("No file uploaded");
  20.     $fc = fread( $fh, filesize($excel_file) );
  21.     @fclose($fh);
  22.     if( strlen($fc) < filesize($excel_file) )
  23.     fatal("Cannot read file");
  24.    
  25.     $time_start = getmicrotime();
  26.     $res = $exc->ParseFromString($fc);
  27.     $time_end = getmicrotime();
  28. }
  29. elseif( $style == 'segment' )
  30. {
  31.     $time_start = getmicrotime();
  32.     $res = $exc->ParseFromFile($excel_file);
  33.     $time_end = getmicrotime();
  34. }


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


  45.     default:
  46.     fatal("Unknown error");
  47. }
  48. //以及讀取完畢,如果沒有錯誤的話就可以循環往MySQL中增加數據了!
  49.     for( $ws_num=0; $ws_num<count($exc->worksheet['name']); $ws_num++ )
  50.     {
  51. //    print "<b>Worksheet: \"";
  52. //    if( $exc->worksheet['unicode'][$ws_num] ) {
  53. //    print uc2html($exc->worksheet['name'][$ws_num]);
  54. //    } else
  55. //    print $exc->worksheet['name'][$ws_num];
  56. //
  57. //    print "\"</b>";
  58.     $ws = $exc->worksheet['data'][$ws_num];
  59. //
  60. //
  61. //     print "<tr><td>&nbsp;</td>\n";
  62.         $namenum=0;
  63.    $costomernumnum=0;
  64.    $phone1num=0;
  65.    $phone2num=0;   
  66.    $address1num=0;
  67.    $address2num=0;
  68.    $companynum=0;
  69.    $levelcnum=0;
  70.    $psnum=0;   
  71.      for( $j=0; $j<=$ws['max_col']; $j++ ) {
  72.     //print "<td class=index>&nbsp;";
  73.     //if( $j>25 ) print chr((int)($j/26)+64);
  74.     //先讀取列名


  75.     $tmpcolum=trim($_POST["$j"]);
  76.     //echo($tmpcolum."|");
  77.     if ($tmpcolum=="name") $namenum=$j;
  78.    if ($tmpcolum=="costomernum") $costomernumnum=$j;
  79.    if ($tmpcolum=="phone1") $phone1num=$j;
  80.    if ($tmpcolum=="phone2") $phone2num=$j;   
  81.    if ($tmpcolum=="address1") $address1num=$j;
  82.    if ($tmpcolum=="address2") $address2num=$j;
  83.    if ($tmpcolum=="company") $companynum=$j;
  84.    if ($tmpcolum=="levelc") $levelcnum=$j;
  85.    if ($tmpcolum=="ps") $psnum=$j;      
  86.      }
  87.      for( $i=0; $i<=$ws['max_row']; $i++ ) {
  88.      //print "<tr><td class=index>".($i+1)."</td>\n";
  89.      if(isset($ws['cell'][$i]) && is_array($ws['cell'][$i]) ) {
  90.      if ($namenum!=0&&$phone1num!=0)//請在這裡指定必須的不為空的字段
  91.      {
  92.         $sql="insert into net_costomer(costomernum,name,company,levelc,phone1,phone2,address1,address2,ps)
  93.    values('".$exc->sst['data'][$ws['cell'][$i][$costomernumnum]['data']]."',
  94.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$namenum]['data']])."',
  95.    '".uc2html($exc->sst['data'][$ws['cell'][$i][companynum]['data']])."',
  96.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$levelcnum]['data']])."',
  97.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$phone1num]['data']])."',
  98.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$phone2num]['data']])."',
  99.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$address1num]['data']])."',
  100.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$address2num]['data']])."',
  101.    '".uc2html($exc->sst['data'][$ws['cell'][$i][$psnum]['data']])."')";
  102.      echo($sql."<br>");
  103.      }
  104.      //$conn->Query($sql);
  105.          }
  106.          }
  107.          }
  108. //導入完成刪除文件
  109. unlink($filename);


  110. }
複製代碼

你注意沒有,我把執行的那一行註釋掉的,只要去掉註釋就可以正確執行了!
如下圖片:
詳細的補充整理代碼在附件中!
MSN:woff5678@hotmail.com




 

臉書網友討論

全部文件(需要自己根据需要修改调试).rar

83.16 KB, 下載次數: 331

phpexcelparser4.rar

96.6 KB, 下載次數: 0

售價: 5 金T幣  [記錄]  [購買]

UTF8編碼

2#
發表於 2012-9-23 16:38:18 | 只看該作者
不回不行了,因为楼猪太有才了。

版主招募中

*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-4-29 07:46 , Processed in 0.079767 second(s), 26 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表