我一直在尝试上传和读取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
它上传OK,但在尝试读取文件时出现此错误:
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.
我使用的代码与此类似:
vb.net traversing an xls / xlsx file?
因此连接如下:
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
所以看起来它正在上传并打开文件OK,但没有读取行....
我不确定为什么会发生这种情况!
任何帮助将非常感激!
ACE是残酷的,一直有麻烦,它不能同时存在于32位和64位版本的系统上。结果我根本就不使用它。
要读取Excel XLSX文件,我使用“EPPlus”,这已被证明非常容易处理和极其高效。
它只适用于XLSX(不是XLS)
示例...(简单地将第一张纸拉出作为数据表)
Public Function XlsxToDataTable(byteStream As IO.MemoryStream) As DataTable
Using pac As New OfficeOpenXml.ExcelPackage(byteStream)
Dim wb As OfficeOpenXml.ExcelWorkbook = pac.Workbook
Dim ws As OfficeOpenXml.ExcelWorksheet = wb.Worksheets(1) '1 based
Dim out As New DataTable
For iC As Integer = 1 To ws.Dimension.End.Column
out.Columns.Add(ws.Cells(1, iC).Value.ToString)
Next
For iR As Integer = 2 To ws.Dimension.End.Row
Dim nr As DataRow = out.NewRow
For iC As Integer = 1 To ws.Dimension.End.Column
nr(iC - 1) = ws.Cells(iR, iC).Value
Next
out.Rows.Add(nr)
Next
Return out
End Using
End Function