顯示具有 ASP 標籤的文章。 顯示所有文章
顯示具有 ASP 標籤的文章。 顯示所有文章

2020年4月29日 星期三

在GridView中加入自動編號的序號

參考: https://blog.xuite.net/xiaolian/blog/46204394-%E5%9C%A8GridView%E4%B8%AD%E5%8A%A0%E5%85%A5%E8%87%AA%E5%8B%95%E7%B7%A8%E8%99%9F%E7%9A%84%E5%BA%8F%E8%99%9F

在Aspx檔案中GridView表格內插入一個欄位,在第一欄加上TemplateField的欄位,語法如下:

流水號從第一筆編起
  <asp:TemplateField HeaderText="序號">
          <ItemTemplate>
             <%#GridView1.PageIndex * GridView1.PageSize + GridView1.Rows.Count + 1%>
           </ItemTemplate>
           <HeaderStyle Wrap="False"  />
            <ItemStyle  HorizontalAlign="Center" VerticalAlign="Middle" />
  </asp:TemplateField>

OR

  <asp:TemplateField HeaderText="序號">
         <ItemTemplate>
            <%#Container.DataItemIndex + 1%>
         </ItemTemplate>
         <HeaderStyle Wrap="False"  />
         <ItemStyle  HorizontalAlign="Center" VerticalAlign="Middle" />
  </asp:TemplateField>


流水號每頁從1編起
   <asp:TemplateField HeaderText="序號">
           <ItemTemplate>
              <%#Container.DisplayIndex + 1%>
            </ItemTemplate>
            <HeaderStyle Wrap="False"  />
            <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
   </asp:TemplateField>
 

2015年10月12日 星期一

會員登入驗證



[會員登入] 如何判別有無這位會員?...DataReader的 HasRows屬性與 .Read()方法


如何利用 Visual Studio 查詢資料庫
http://www.dotblogs.com.tw/yc421206/archive/2009/06/10/8776.aspx


HOW TO:使用 ADO.NET 和 Visual Basic .NET 與資料庫連線並且執行指令

https://support.microsoft.com/zh-tw/kb/301075






Hello i am trying to create a login and session script with php to use for sql server and i cannot get it to work, it seams like no mater what i put into the login form aslong as it validates it will work, i cannot figure out what is wrong with the code however, i've just resently started using php and sql server and have not gotten the knowlage to figure out the problem for my self if soeone could help that would be great, also if you knwo any good tutorial sites that use sql server and php could you please share as there doesnt seam to be that many good tutorial sites for them sadly. any help is much welcomed at this stage. my main problem is, is that it isnt checking if the information posted in the html form exists in the database. (i have taken out the js validation as it doesnt seam nessessary however that works)
Login.html
name="log" action="log_action.php" method="post"> Username: class="form" type="text" name="uNm"> /> Password: class="form" type="password" name="uPw"> /> name="submit" type="submit" value="Submit">
log_action.php
session_start();
$serverName = "(local)";
$connectionInfo = array("Database"=>"mydatabase","UID"=>"myusername", "PWD"=>"mypassword");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false){
    echo "Error in connection.\n";
    die( print_r( sqlsrv_errors(), true));
}
$username = $_REQUEST['uNm'];
$password  = $_REQUEST['uPw'];
$tsql = "SELECT * FROM li WHERE uNm='$username' AND uPw='$password'";
$stmt = sqlsrv_query( $conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if($stmt == true){
    $_SESSION['valid_user'] = true;
    $_SESSION['uNm'] = $username;
    header('Location: index.php');
    die();
}else{
    header('Location: error.html');
    die();
}
index.php
php
session_start();
if($_SESSION['valid_user']!=true){
    header('Location: error.html');
    die();
}
?>
Thank you for any help you guys might be able to bring

********
php

#starts a new session
session_start();

#includes a database connection
include 'connection.php';

#catches user/password submitted by html form
$user = $_POST['user'];
$password = $_POST['password'];

#checks if the html form is filled
if(empty($_POST['user']) || empty($_POST['password'])){
    echo "Fill all the fields!";
}else{

#searches for user and password in the database
$query = "SELECT * FROM [DATABASE_NAME].[dbo].[users] WHERE user='{$user}' AND"
         ."password='{$password}' AND active='1'";
$result = sqlsrv_query($conn, $query);  //$conn is your connection in 'connection.php'

#checks if the search was made
if($result === false){
     die( print_r( sqlsrv_errors(), true));
}

#checks if the search brought some row and if it is one only row
if(sqlsrv_has_rows($result) != 1){
       echo "User/password not found";
}else{

#creates sessions
    while($row = sqlsrv_fetch_array($result)){
       $_SESSION['id'] = $row['id'];
       $_SESSION['name'] = $row['name'];
       $_SESSION['user'] = $row['user'];
       $_SESSION['level'] = $row['level'];
    }
#redirects user
    header("Location: restrict.php");
}
}

?>






"ss2g6", "UID"=>"ss2g6", "PWD"=>"group6", 'ReturnDatesAsStrings'=> true );
$conn = sqlsrv_connect( $server, $connectionInfo );

if ($conn == false){
  die( print_r( sqlsrv_errors(), true));
}
$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );

/* Update GET */
if(isset($_GET['update'])){
    $updatePatientId = $_GET['patientId'];
    $sql = "SELECT * FROM Patient WHERE patientId = $updatePatientId";
    $result = sqlsrv_query($conn, $sql, $params, $options);
    $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC);

 $updateAge = $row['age'];
    $updateName = $row['name'];
    $updateAddress = $row['address'];
    $updateDoctorId = $row['doctorId'];
}


/* Update POST */
if (isset($_POST['Update'])){
    $updatePatientIdOld = $_POST['updatePatientIdOld'];
 $updateAge = $_POST['age'];
    $updateName = $_POST['name'];
    $updateAddress = $_POST['address'];
    $updateDoctorId = $_POST['doctorId'];
    
    if( $updateName == "" || $updateAddress == "" || $updateDoctorId == ""){
  $validation_error = true;
 }
 else {
  $validation_error = false;
 }
 
 if(is_numeric($updateAge) || is_numeric($updateDoctorId)){
  $numeric = true;
 }
 else {
  $numeric = false;
    }

    if ($validation_error || !$numeric){
        $update_error = true;
    }
 
    if (!isset($update_error)){
        $sql = "UPDATE Patient SET age=$updateAge, name='$updateName', address = '$updateAddress', doctorId =$updateDoctorId WHERE patientId = $updatePatientIdOld";
        $result = sqlsrv_query($conn, $sql, $params, $options);
        $result = sqlsrv_query( $conn, $sql, $params);
 if ($result == false){
   if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
 }
 else{
        $rowsAffected = sqlsrv_rows_affected ($result);
 
     if ($rowsAffected == false){
       $error = true;     
     }
     else{
      $error = false;
     }
   }
     $confirm = "The patient information is updated.";
    }
}
if(isset($_POST['Insert'])) {
    $age = $_POST['age'];
    $name = $_POST['name'];
    $address = $_POST['address'];
    $doctorId = $_POST['doctorId'];
 
 /* check empty fields */
 if($age == "" || $name == "" || $address == ""){
  $validation_error = true;
 }
 else {
  $validation_error = false;
 }
 
 /*check whether age is a numeric number */
 if(is_numeric($age)){
  $numeric = true;
 }
 else {
  $numeric = false;
 } 
 
    $sql = "INSERT INTO Patient VALUES ('$age', '$name', '$address', '$doctorId')";
 
  if($validation_error == false && $numeric == true){
    $params = array();
    $result = sqlsrv_query( $conn, $sql, $params);
 if ($result == false){
   if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
 }
 else{
        $rowsAffected = sqlsrv_rows_affected ($result);
 
     if ($rowsAffected == false){
       $error = true;     
     }
     else{
      $error = false;
     }
   }
 
    $confirm = "The Patient information is inserted.";
 }
 else {
  $confirm = "";
 }
 
}

if(isset($_GET['delete'])){
 $patientId = $_GET['patientId'];
 $sql = "DELETE FROM Patient WHERE patientId = '". $patientId . "'";
 $params = array();
    $options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
    $result = sqlsrv_query( $conn, $sql, $params);
 if ($result == false){
        if(($errors = sqlsrv_errors()) != null){
            $error_msg = "";
            foreach($errors as $error){
                $error_msg = $error_msg . " " . cut_string_using_last(']', $error['message'], 'right', false);
            }
        }
 }
 else{
        $rowsAffected = sqlsrv_rows_affected ($result); 
     if ($rowsAffected == false){      
       $error = true;     
     }
     else{      
      $error = false;
     }
   }
 

}

if (isset($_POST['submit'])){
    $sql1 = $_POST['query'];
}
else
{
    $sql = "SELECT * FROM Patient";
}

$params = array();
$options =  array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $sql , $params, $options );
?>



    

    

Patient


"; } if($validation_error){ $msg = $msg . "No text fields can be empty"; } if(isset($error_insert) && $error_insert){ $msg = "Data cannot be inserted, foreign key constraints or triggers violated "; } if (isset($error_msg)){ ?>
""){ ?>
"; } if($validation_error){ $msg = $msg . "No text fields can be empty"; } if(isset($error_insert) && $error_insert){ $msg = "Data cannot be inserted, foreign key constraints or triggers violated "; } if (isset($error_msg)){ ?>
""){ ?>
Patient ID




http://206-web-interface.googlecode.com/svn-history/r83/trunk/patients.php




2015年10月6日 星期二

產生不重複的亂數


https://tw.answers.yahoo.com/question/index?qid=20051105000014KK03021

Randomize() 

'設定範圍 
intRangeSize = (49 - 1) + 1 

'取亂數 
sngRandomValue = intRangeSize * Rnd() 

' 結果再加上 1 
sngRandomValue = sngRandomValue + 1 

' 轉換型別後就是答案. 
intRandomInteger = Int(sngRandomValue) 

產生六個且不重複的話,就重複產生六次,每次都去檢查看是否重複,重複就再產生一次,把結果紀錄下來就行了. 




http://www.blueshop.com.tw/board/FUM20050124192253INM/BRD20060404152231MBG.html


http://fabricekds.blogspot.tw/2008/06/asp.html




2014年5月29日 星期四

如何產生DLL檔部暑網站


Precompiled Web Site 是指編譯過的網站,在 .NET 1.x 是由 Visual Studio 處理, .NET 2.0 多了一個新的 aspnet_compiler.exe 工具程式(含在 .NET Framework 中),讓開發人員可以在沒有 Visual Studio 環境下,可以對它進行編譯,和 Visual Studio 的 Publish Web Site 是一樣的,只是要手動處理所有事情 .

-----------
下列命令會就地編譯 WebApplication1 應用程式:
Aspnet_compiler -v /WebApplication1
下列命令會就地編譯 WebApplication1 應用程式。已編譯的應用程式也會包含偵錯資訊,如果其中報告發生錯誤,則工具會加入堆疊追蹤資訊。
Aspnet_compiler -v /WebApplication1 -d -errorstack
下列命令會使用實體目錄路徑,編譯供部署使用的 WebApplication1 應用程式,也會在輸出組件中加入兩個屬性。它會使用 -keyfile 選項加入AssemblyKeyFileAttribute 屬性,以指定 Key.sn 檔包含公開/私密金鑰組資訊,而工具可以將該資訊用於所產生組件的強式名稱。此命令也會使用 -aptca 選項,在產生的組件中加入 AllowPartiallyTrustedCallersAttribute 屬性。編譯的 Web 應用程式是建立於 c:\applicationTarget 目錄中。
Aspnet_compiler -v /WebApplication1 -p c:\Documents and Settings\Default\My Documents\MyWebApplications\WebApplication1 -keyfile c:\Documents and Settings\Default\My Documents\Key.sn -aptca c:\applicationTarget
下列命令會編譯預設 Metabase 路徑下的 WebService2 服務,以編譯的應用程式覆寫 SampleWebService 目標目錄。
Aspnet_compiler -m LM/W3SVC/1/ROOT/WebService2 -f c:\InetPub\wwwroot\SampleWebService

2014年5月19日 星期一

Gridview刪除時做確認

<asp:TemplateField ShowHeader="False"> <ItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CssClass="btnlink" CommandName="Delete" Text="刪除" OnClientClick="return confirm('是否刪除?');" ></asp:LinkButton> </ItemTemplate> </asp:TemplateField>

2014年5月9日 星期五

GridView 動態產生欄位 For C#

資料來源:
http://www.blueshop.com.tw/board/fum20041006161839lrj/BRD2011031411333152E.html

事先(page_init)建立所有的欄位,

事後(page_load, button_click, .....)隱藏某幾個已存在的欄位 

GridView密技#4---使用ITemplate介面,動態新增「GridView樣版列(Template Row/模版列)」,內含VB與C#語法

http://www.dotblogs.com.tw/mis2000lab/archive/2008/12/24/gridview_dynamic_add_template_1224.aspx

GridView密技#5---(修改/補強版)使用ITemplate介面,動態新增「GridView樣版列(Template Row/模版列)」
http://www.dotblogs.com.tw/mis2000lab/archive/2008/12/24/gridview_dynamic_add_template_1224.aspx 


Q:自訂GridView欄位,為何每換頁一次,欄位就一直增加呢?
資料來源:
http://www.blueshop.com.tw/board/FUM20041006161839LRJ/BRD20101117120721FD2.html


protected void Page_Init()
{
dt.clear(); // 加一行
dt = sqlDB.DbCreateDataTable(sql, "Grid1");

-------

我想可能是「GridView的 DataBinding時機有錯」

如果您寫在 Page_Load()事件裡面,
多寫一段判別式,說不定就改善了。
IF Not Page.IsPostBack Then
'----把 DBInit()程式寫在這裡
End IF

DBInit()就是您目前 Page_Init()這一區塊的程式碼。

關於 Page的生命週期,PostBack的觀念,Page_Load()事件何時被觸發?
您可以參考這 2篇文章,希望對您有幫助。

[FAQ]GridView的編輯、修改、刪除,為何都會重複執行兩次?
http://www.dotblogs.com.tw/mis2000lab/archive/2009/10/20/11157.aspx


自己動手寫 GridView的編輯/更新程式,但抓不到修改後的資料?(兼論DataBinding的時機)
http://www.dotblogs.com.tw/mis2000lab/archive/2009/11/09/11497.aspx 

------

把addSource();從Page_Load移到Page_Init.
並且把中斷點放在Page_Init的addSource(),但發現一個問題.
當我按下送出的時候 此時畫面會PostBack 這個時候,Page_Init也是會被執行,且會再次觸發.
您試會嗎?如果不會,是我這裡有什麼東西沒設定到嗎?

後端程式如下:

protected void Page_Init(object sender, EventArgs e)
{
addSource();
}

protected void Page_Load(object sender, EventArgs e)
{
}

private void addSource()
{
ddlTest1.Items.Add(new ListItem("s1", "1"));
ddlTest1.Items.Add(new ListItem("s2", "2"));
ddlTest1.Items.Add(new ListItem("s3", "3"));


GridView依前方欄位值條件disable編輯及刪除鈕

資料來源:
http://adamschen9921.pixnet.net/blog/post/91648159-gridview%E4%BE%9D%E5%89%8D%E6%96%B9%E6%AC%84%E4%BD%8D%E5%80%BC%E6%A2%9D%E4%BB%B6disable%E7%B7%A8%E8%BC%AF%E5%8F%8A%E5%88%AA%E9%99%A4%E9%88%95

本例依前方欄位值條件,如未鎖則可編輯及刪除,如前方欄位為已鎖,則停用編輯及刪除。
GridView進行RowDataBound時,檢查Cell值為已鎖或未鎖並決定是否Disable編輯及刪除之功能。
 
 
 
VB

Private Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)Handles Gridview1.RowDataBound
If e.Row.Cells(6).Text.Trim() = "已鎖" Then
DirectCast(e.Row.Cells(7).Controls(0), WebControl).Enabled = False
DirectCast(e.Row.Cells(8).Controls(1), WebControl).Enabled = False
End If
End Sub


C#

private void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.Cells[6].Text.Trim() == "已鎖") {
((WebControl)e.Row.Cells[7].Controls[0]).Enabled = false;
((WebControl)e.Row.Cells[8].Controls[1]).Enabled = false;
}
}

2014年5月2日 星期五

GridView設定


Q1:內建的DeleteQuery刪除時卻出現錯誤:必須宣告純量變數


Q2: 只要顯示日期
時間欄位轉換為TemplateField, 設定 {0:d}
-------------------
Bind("配宿時間", "{0:d}")
--------------------

Q3:刪除資料,並彈出刪除確認對話框
http://blog.finalevil.com/2008/11/aspnetgridview03.html


2014年4月22日 星期二

ASP.NET 2.0:利用Master Page打造網頁的樣版



資料來源:http://www.iiiedu.org.tw/taipei/student/paper/tihs10r.htm

ASP.NET 2.0:利用Master Page打造網頁的樣版


 
· 摘要
  使用樣版(Template)的觀念來設計網頁是一個很重要的技巧,因為同一個網站的網頁通常需要使用相同的樣式與風格,以便讓網站的使用者使用起來有一致的感覺,開發ASP網頁的程設計師可以使用#include檔案的技巧引入一個共用的檔案當做網頁的開頭、結尾、或是左右兩邊的功能表或廣告,讓所製作的每一個網頁擁有一致的介面,達到樣版的功能,而且也可以縮短設計網頁操作介面的時間,讓網頁容易維護。ASP.NET網頁的程設計師可以使用User Control製作每一個網頁欲使用的開頭、結尾、或是左右兩邊的功能表或廣告當做樣版,再拿給每一個網頁使用,讓同一個網站的每一個網頁都可以有一致的操作介面和感覺,當然也可以得到縮短設計網頁操作介面的時間,使網站易於維護,除此之外,使用User Control設計的ASP.NET的網頁還可以經由把User Control放置到快取記憶體的做法來改善將網頁的內容顯示給網際網路使用者瀏覽的效能,但是#include 檔案和使用User Control來製作樣版功能都不是網頁設計工具內建的做法,也就是說要靠網頁的設計師自行套用才能享受利用樣版設計網頁的好處,針對這一點,ASP.NET 2.0提出一個新的功能,Master Page,讓網頁設計師可以採用視覺編輯的方式設計網站中每一個網頁欲套用的樣版,再套用到網站中每一個網頁,達到風格一致的效果,縮短網頁的設計和維護的時間,提升網頁開發的生產力。本文將帶領大家一探ASP.NET 2.0的Master Page功能的奧秘,並使用ASP.NET 2.0提供的Master Page樣版功能快速開發風格一致的網頁。
 
˙[特別注意] 本文中的示範是採用Visual Studio 2005 Beta 1版製作的,其程式的寫法與程式開發工具的使用方法可能會和最終讀者拿到的Visual Studio 2005正式版產品有所出入,您所看到的操作功能表和操作畫面也會和您使用Visual Studio 2005時採用那一種開發工具的操作習慣而稍有不同。
 
 · 認識Master Page和Content Page
  ASP.NET 2.0提出的Master Page和Content Page的觀念,可以幫助網頁的設計者快速地設計網頁的樣版,例如網頁的設計者想要讓網頁中的每一個網頁都具有相同的頁首、頁尾、左方功能表、以及右方的廣告超連結,就可以設計類似圖1的Master Page:
 
 圖1:Master Page與Content Page
  圖1中的頁首、頁尾、左方功能表、以及右方的廣告超連結就是Master Page的結構,而中央空白的地方就是放置內容網頁(即Content Page)的地方,網頁設計者只要更換合適的內容網頁就可以快速製作出一堆風格與樣式一致的網頁,其概念和做法類似ASP網頁的#include檔案和ASP.NET 1.X的User Control的做法,只不過是利用ASP.NET 2.0內建的Master Page來製作而已。了解Master Page的用途之後,接下來我們就要使用Visual Studio 2005提供的Master Page功能建立一個網頁風格一致的網站。
 
建立Master Page
首先使用[Project]功能表底下的[New]功能底下的[Web Site]功能建立一個ASP.NET網站,然後使用滑鼠的右鍵點中[Solution Explorer]視窗中的專案,選擇出現的功能表中的[Add New Item]功能,再從出現的視窗中選擇[Master Page]項目,表示要為網站加入Master Page,如圖2所示:
 
圖2:為網站加入Master Page的畫面
  
   在[Name]欄位中輸入Master Page檔案的名稱之後按下[Add]鍵,Visual Studio 2005就會為我們的網站加入一個Master Page,其副檔名預設為(*.master),並開啟剛加入的Master Page供您編輯,請注意其中的<% master %>標籤,表示這是一個Master Page,其中可以放置任何的HTML元素和Server控制項,包括、、和
等標籤,以及ASP.NET 2.0新加入的控制項,負責顯示內嵌的Content Page。您可以使用滑鼠的左鍵點選畫面左下方的[Design]頁籤,表示要對Master Page進行視覺編輯。  Master Page中最常見的結構就是Table,在Master Page中放入Table可以控制整個樣版的元素擺放位置,例如您可以於Table的上方放入負責顯示公司商標的元素,和瀏覽網站中其他網頁的超連結,於Table的下方放入版權聲明。


2014年4月15日 星期二

Excel匯入SQL

[ASP.net/MSSQL] 讀寫Office Excel之前要做的相關設定









Client side 
<asp:FileUpload ID="FileUploadQuestion" runat="server" Width="30%"/>
<asp:Button ID="ButtonUpload" runat="server" Text="匯入"/>



Server side 
Imports System.Data.OleDb
Imports System.Data

Partial Class Test
' 按下『匯入』鈕
  Protected Sub ButtonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonUpload.Click
Dim FileUpload As FileUpload ' 抓取Client Side的檔案
    Dim OLEConn As OleDbConnection ' 與Excel連繫用
    Dim OLECommand As OleDbCommand
    Dim OLEDataAdapter As OleDbDataAdapter
    Dim dsResult As New Data.DataSet ' 存放Excel的資料內容
    Dim dtResult As New Data.DataTable
    Dim FileName As String = "" ' Client Side的檔案名稱
    Dim StartIndex As Integer = 0
    Dim ExcelConn As String = "" ' 與Excel連繫用
    Dim ExcelSelect As String = ""
    Dim Field1 As String = "" ' Primary Key
    Dim Field2 As String = ""
    Dim Field3 As Integer = 0
    Dim Field4 As String = ""
    Dim Field5 As String = ""
    Dim Field6 As String = ""
    Dim Field7 As String = ""
    Dim Field8 As String = ""
    Dim SqlString As String = "" ' 組新增至資料庫的SQL指令
    Dim InsertSuccCount As Integer = 0 ' 匯入成功筆數
    Dim InsertFailCount As Integer = 0 ' 匯入失敗筆數

    Try
      FileUpload = CType(Me.FindControl("FileUploadQuestion"), FileUpload)
      FileName = FileUpload.PostedFile.FileName
      If FileName = "" Then
        ' ut.MessageBox("請選取一份欲匯入的Excel檔案!", MsgBoxStyle.Information, Me.Page)
        Exit Sub
      Else
        StartIndex = FileName.LastIndexOf(".") + 1
        If FileName.Substring(StartIndex, 3) <> "xls" Then
          ' ut.MessageBox("請確認欲匯入的檔案格式為Excel!", MsgBoxStyle.Information, Me.Page)
          Exit Sub
        End If
      End If

      ExcelConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileName & ";Extended Properties=EXCEL 8.0"
      ExcelSelect = "SELECT * FROM [Sheet1$]"

      OLEConn = New OleDbConnection(ExcelConn)
      OLECommand = New OleDbCommand(ExcelSelect, OLEConn)
      OLEDataAdapter = New OleDbDataAdapter(OLECommand)
      OLEConn.Open()
      OLEDataAdapter.Fill(dsResult, "exceltogrid")
      OLEConn.Close()
      dtResult = dsResult.Tables("exceltogrid")

      If dtResult.Rows.Count > 0 Then
        For i As Integer = 0 To dtResult.Rows.Count 1
                 Field1 = dtResult.Rows(i).Item(0).ToString.Trim
            If Field1 <> "" Then
              Field2 = dtResult.Rows(i).Item(1).ToString.Trim
Field3 = Convert.ToInt32(dtResult.Rows(i).Item(2).ToString.Trim)
Field4 = dtResult.Rows(i).Item(3).ToString.Trim
Field5 = dtResult.Rows(i).Item(4).ToString.Trim
              Field6 = dtResult.Rows(i).Item(5).ToString.Trim
              Field7 = dtResult.Rows(i).Item(6).ToString.Trim
              Field8 = dtResult.Rows(i).Item(7).ToString.Trim

              SqlString = "INSERT INTO TestTable (Field1, Field2, Field3, Field4, Field5, Field6, Field7, Field8) VALUES ('" & Field1 & "', '" & Field2 & "', " & Field3 & ", '" & Field4 & "', '" & Field5 & "', '" & Field6 & "', '" & Field7 & "', '" & Field8 & "')"

' 呼叫貴單位新增資料庫的函數
              If ExecuteInsert(SqlString) Then
                InsertSuccCount += 1
              Else
                InsertFailCount += 1
              End If
            Else
              Exit For
            End If
        Next

        ' ut.MessageBox("匯入成功筆數:" & InsertSuccCount.ToString & ".失敗筆數:" & InsertFailCount.ToString, MsgBoxStyle.Information, Me.Page)
' 此處可寫重新查詢GridView的Code,讓user看到匯入成功後的結果
      End If
    Catch ex As Exception
      ' ut.MessageBox(ex.ToString, MsgBoxStyle.Information, Me.Page)
      Exit Sub
    End Try
End Sub
End Class

Excel格式: 

A
B
C
D
E
F
G
H
1
Field1 Title 
Field2 Title
Field3 Title
Field4 Title
Field5 Title
Field6 Title
Field7 Title
Field8 Title
2
A
AA
1
AAA
AAAA
AAAAA
AAAAAA
AAAAAAA
3
B
BB
2
BBB
BBBB
BBBBB
BBBBBB
BBBBBBB
4
C
CC
3
CCC
CCCC
CCCCC
CCCCCC
CCCCCCC
5
D
DD
4
DDD
DDDD
DDDDD
DDDDDD
DDDDDDD
6
E
EE
5
EEE
EEEE
EEEEE
EEEEEE
EEEEEEE