2014-04-22 81 views

回答

0

我做了一個Excel文件的導入,在過去幾天更新一個SQL Server表(與DevExpress的網格只顯示導入的數據)。
我我的例子,我:

  1. 詢問用戶名(不是必要的,如果你已經知道 文件名和路徑)
  2. 負荷的Excel文件中所需要的數據表(沒有的DevExpress那)
  3. 顯示在DevExpress的網格數據表,然後

注:在現實生活中,我使用電網只能查看/控制加載的數據。
然後,我從數據表中加載的數據更新SQL服務器上的現有數據表(此處不包含代碼)。
注意:在這個例子中,工作表名稱始終是「工作表Sheet1」 - 也許你想在工作表名稱也爲您的方案變量...

注意:您不需要DevExpress的,如果你只想要將Excel文件導入到DataTable中(請參閱下面的代碼中的ImportTable = ReadExcelIntoDataTable(cFileName,「Sheet1」)和函數ReadExcelIntoDataTable())。

' Chose the Excel-File over Open FileDialog() 
    ' If you don't know the filename & path allready 
    Dim cFileName As String = "" 
    Dim filedialog As OpenFileDialog = New OpenFileDialog() 
    filedialog.Title = "Chose the File" 
    filedialog.DefaultExt = ".XLSX" 
    filedialog.ShowDialog() 
    cFileName = filedialog.FileName 
    ' 
    If Not cFileName = "" Then 
     ImportTable = ReadExcelIntoDataTable(cFileName, "Sheet1") 
     If ImportTable.Rows.Count > 0 Then 
      Grid_Datenimport.DataSource = ImportTable 
     ' Do some format (if you like).. 
     GridView2.Columns("ColumnX").DisplayFormat.FormatType = DevExpress.Utils.FormatType.DateTime 
     GridView2.Columns("ColumnX").DisplayFormat.FormatString = "dd/MM/yyyy HH:mm:ss" 
      GridView2.Columns("ColumnX").Width = 160 
     End If 
    End If 

    Public Shared Function ReadExcelIntoDataTable(ByVal FileName As String, ByVal SheetName As String) As DataTable 
     Dim RetVal As New DataTable 
     Dim strConnString As String 
     strConnString = "Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};DBQ=" & FileName & ";" 
     Dim strSQL As String 
     strSQL = "SELECT * FROM [" & SheetName & "$]" 
     Dim y As New Odbc.OdbcDataAdapter(strSQL, strConnString) 
     y.Fill(RetVal) 
     Return RetVal 
    End Function 
相關問題