我一直在尝试上传和读取 Excel 文件(.xls 或 .xlsx)
我正在使用以下代码成功上传:
Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
Dim filepath As String = ""
If FileUpload1.HasFile Then
Try
Dim filename As String = FileUpload1.PostedFile.FileName
Dim extension = (filename.Substring(filename.LastIndexOf("."), (filename.Length() - filename.LastIndexOf("."))))
If extension = ".xlsx" Or extension = ".xls" Then
filepath = "\" & Common.toUnix(Now) & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
' ==== NOW READ THE FILE
Else
StatusLabel.InnerText = "Only Excel file types are accepted (.xls/.xlsx)<br> File Uploaded had extension: " & extension
End If
Catch ex As Exception
StatusLabel.InnerText = "Upload status: The file could not be uploaded. The following error occured: " + ex.ToString()
End Try
End If
End Sub
它可以上传,但是在尝试读取文件时出现此错误:
System.Data.OleDb.OleDbException (0x80004005): The Microsoft Jet database engine cannot open the file ''. It is already opened exclusively by another user, or you need permission to view its data.
我正在使用类似于此的代码阅读:
因此连接如下:
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _
";Data Source=" & ExcelFile & _
";Extended Properties=Excel 8.0;"
Dim conn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Dim excelDataSet As New DataSet()
Try
conn = New OleDbConnection(connString)
conn.Open() '<<< ERROR IS RAISED ON THIS LINE
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets(dt.Rows.Count) As String
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheets(i) = row("payments").ToString
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
If i = SheetNumber Then
Exit For
End If
Next
..................
我正在上传到共享服务器,因此无法控制此类权限,但我确实具有读/写权限并且上传图像工作正常,但它正在读取我无法开始工作的这个文件。
笔记
.xls 文件会发生此错误,使用 .xlsx 时会出现此错误:
System.Data.OleDb.OleDbException (0x80004005): Cannot update. Database or object is read-only. at System.Data.OleDb.OleDbConnectionInternal
此错误发生在此行:
For Each row As DataRow In dt.Rows
所以看起来它正在上传并打开文件正常,但没有读取行......
我也不知道为什么会这样!
任何帮助将非常感激!