尝试从VB.Net中的网页读取时,无法在excel文件中找到引用的工作表

时间:2013-03-14 15:07:58

标签: asp.net vb.net excel oledb

我正在尝试构建一个允许用户选择excel文件的网页,然后页面将读取页面内容并在验证后将数据上传到数据库。

我有一个fileUpload asp控件,带有一个执行按钮和一个gridview来显示数据。这不是最终目标,但我只是测试脚本是否正在成功读取文件(不是这样)。

我不断得到的错误是:

"The Microsoft Office Access database engine could not find the object 'Sheet1'. Make sure the object exists and that you spell its name and the path name correctly."

我上传的excel文件肯定有Sheet1,所以我不确定发生了什么。

我不会假装有很多经验或理解OleDB如何工作,所以我确信这很简单。

我的代码如下:

Protected Sub Upload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Upload.Click
    If (testFile.HasFile) Then
        Dim conn As OleDbConnection
        Dim cmd As OleDbCommand
        Dim da As OleDbDataAdapter
        Dim ds As DataSet
        Dim query As String
        Dim connString As String = ""
        Dim strFileType As String = System.IO.Path.GetExtension(testFile.FileName).ToString().ToLower()

        'Check file type
        If strFileType.Trim = ".xls" Or strFileType.Trim = ".xlsx" Then
        Else
            MsgBox("Only excel files allowed")
            Exit Sub
        End If

        Try
            'Connection String to Excel Workbook
            If strFileType.Trim = ".xls" Then
                connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & testFile.FileName & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
            ElseIf strFileType.Trim = ".xlsx" Then
                connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & testFile.FileName & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
            End If

            query = "SELECT * FROM [Sheet1$]"

            'Create the connection object
            conn = New OleDbConnection(connString)
            'Open connection
            If conn.State = ConnectionState.Closed Then conn.Open()
            'Create the command object
            cmd = New OleDbCommand(query, conn)
            da = New OleDbDataAdapter(cmd)
            ds = New DataSet()
            da.Fill(ds)

            grvExcelData.DataSource = ds.Tables(0)
            grvExcelData.DataBind()

            da.Dispose()
            conn.Close()
            conn.Dispose()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    Else
        MsgBox("Must have file")
        Exit Sub
    End If
End Sub

我也很欣赏如何了解有关OleDB的更多信息以及我的代码的具体错误!

谢谢!

1 个答案:

答案 0 :(得分:0)

您需要创建一个输出来查看页面中的工作表,可能是在DropDownList对象中(此代码有点难看,但应该指向正确的方向)。基本上首先返回您的工作表以验证它是否存在...

 private void ProcessExcelFile(string fileName, bool isOpenXMLFormat)
    {
        string fn = System.IO.Path.GetFileName(fileName);
        String RelativePath = "YourPath/" + fn;
        string connectionString = String.Empty;
        OleDbConnection con;

        if (isOpenXMLFormat)
            //read a 2007 file  
            connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                fileName + ";Extended Properties=\"Excel 8.0;HDR=YES;\"";
        else
            //read a 97-2003 file  
            connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                fileName + ";Extended Properties=Excel 8.0;";

        con = new OleDbConnection(connectionString);
        con.Open();

        //get all the available sheets  
        System.Data.DataTable dataSet = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

        //get the number of sheets in the file  
        string[] workSheetNames = new String[dataSet.Rows.Count];
        int i = 0;
        foreach (DataRow row in dataSet.Rows)
        {
            //insert the sheet's name in the current element of the array  
            //and remove the $ sign at the end  
            //workSheetNames[i] = row["TABLE_NAME"].ToString().Trim(new[] { '$' });
            workSheetNames[i] = row["TABLE_NAME"].ToString();
            i++;
        }
        SheetNames.DataSource = workSheetNames;
        SheetNames.DataBind();