1

我已经开始使用 asp.net 开发一个网站。

我需要从 excel 中获取一些数据以将其显示给客户端。

我在 somee.com 上托管我的网站,以便我可以自由地托管它。

但是在 somee.com 的服务器上没有安装 Excel。

我已经为我的网站编写了一些代码来显示来自 excel 的数据。

Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
    Dim xlWorkbook As Microsoft.Office.Interop.Excel.Workbook = xlApp.Workbooks.Open(FileUploadPath & sender.text)
    Dim xlWorksheet As Microsoft.Office.Interop.Excel._Worksheet = xlWorkbook.Sheets(SheetName)
    Dim xlRange As Microsoft.Office.Interop.Excel.Range = xlWorksheet.UsedRange

    Dim rowCount As Integer = xlRange.Rows.Count
    Dim colCount As Integer = xlRange.Columns.Count

    Dim tbl As New DataTable()

    For i As Integer = 1 To rowCount
        tbl.Rows.Add()
    Next

    For i As Integer = 1 To colCount
        tbl.Columns.Add()
    Next

    If rowCount > 1 Or colCount > 1 Then
        For i As Integer = 1 To rowCount
            For j As Integer = 1 To colCount
                tbl.Rows(i - 1)(j - 1) = xlRange.Value2(i, j)
            Next j
        Next i
    End If

    gvReadFiles.AutoGenerateColumns = True
    gvReadFiles.DataSource = tbl
    gvReadFiles.DataBind()

    xlApp.ActiveWorkbook.Close(False, Session(FileUploadPath & sender.text))
    xlApp.Quit()

    xlWorkbook = Nothing
    xlApp = Nothing

现在我需要对代码进行一些更改,因此它不依赖于 excel。

你能帮助我吗?

4

1 回答 1

1

我用谷歌解决了两个多小时。

这是代码

Dim objConn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing

Try

    Dim connString As String = ""

    If Extension = "xls" Or Extension = ".xls" Then

        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 8.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""

    ElseIf Extension = "xlsx" Or Extension = ".xlsx" Then

        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & FileUploadPath & sender.text & ";Extended Properties=" + Convert.ToChar(34).ToString() + "Excel 12.0;HDR=No;IMEX=1" + Convert.ToChar(34).ToString() + ""

    End If

    objConn = New OleDbConnection(connString)

    objConn.Open()

    dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

    Dim firstSheetName As String = "Sheet1"

    If Not dt Is Nothing Then
        Dim excelSheets As [String]() = New [String](dt.Rows.Count - 1) {}

        ' Add the sheet name to the string array.
        For Each row As DataRow In dt.Rows
            firstSheetName = row("TABLE_NAME").ToString().Substring(0, row("TABLE_NAME").ToString.Length - 1)
            Exit For
        Next

    End If

    Return firstSheetName

Catch ex As Exception

    Return "Sheet1"

Finally

    If objConn IsNot Nothing Then
        objConn.Close()
        objConn.Dispose()
    End If
    If dt IsNot Nothing Then
        dt.Dispose()
    End If

End Try
于 2013-05-05T18:19:20.247 回答