且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将excel文件保存在数据库VB.NET中

更新时间:2023-02-15 12:30:10

我不太明白将列表框保存到Access数据库的问题,但是将Excel文件保存到数据库中是什么,这是另一回事。 br />


Excel文件毕竟是一系列字节,因此您读取字节,将数据放入INSERT或UPDATE语句的参数中,打开连接并保存数据。



简而言之,代码看起来像

I don't quite understand the question about saving a list box to Access database, but what comes to saving Excel file into a database, it's another thing.

The Excel file is after all a series of bytes so you read the bytes, place the data into a parameter for INSERT or UPDATE statement, open the connection and save the data.

In short the code could look something like
Dim fs As System.IO.FileStream
Dim sr As System.IO.StreamReader

fs = New System.IO.FileStream("c:\path\excelfile", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)
sr = New System.IO.StreamReader(fs)
Dim bytes(fs.Length - 1) As Byte
fs.Read(bytes, 0, fs.Length)

Try
   Using connection As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=accessfilename")
      Using command As System.Data.OleDb.OleDbCommand = New System.Data.OleDb.OleDbCommand("insert into tablename (columnname) values (?)", connection)
         command.Parameters.Add("@bytes", System.Data.OleDb.OleDbType.Binary, fs.Length).Value = bytes
         connection.Open()
         command.ExecuteNonQuery()
         connection.Close()
      End Using
   End Using
Catch exception As Exception
   ' error handling goes here
End Try