vb .net使用excel自动化将数据粘贴到打开的工作簿中

时间:2013-03-25 08:34:20

标签: vb.net ms-office office-automation

是否可以使用vb.net中的办公自动化将数据粘贴到已打开的工作表中? (我是用oledb做的,但速度很慢。)

        Dim Folder As String = "C:\Users\gm1\Desktop\"
        Dim Filename As String = "Raw2Eng.xlsx"
        Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Folder & "\" & Filename & ";Extended Properties=""Excel 12.0;HDR=YES;"""
        Dim MyConnection As New OleDbConnection(ConnectionString)

        MyConnection.Open()
        Dim cmd1 As New OleDbCommand
        cmd1.Connection = MyConnection
        cmd1.CommandText = "DROP TABLE [Sheet2$A1:E1027]"
        cmd1.ExecuteNonQuery()

        cmd1.CommandText = "CREATE TABLE [Sheet2$A1:E1027] (HiResAngle FLOAT, CH2 FLOAT, CH4 FLOAT, CH5 FLOAT, CH6 FLOAT)"
        cmd1.ExecuteNonQuery()

        For j As Integer = 0 To TrimmedSegmentSize - 1
            sb = New StringBuilder
            sb.Append("INSERT INTO [Sheet2$A" & 1 & ":E" & j + 1 & "] (HiResAngle, CH2, CH4, CH5, CH6) values ( '")
            sb.Append(eng(i, j, 0)) : sb.Append("' , '")
            sb.Append(eng(i, j, 1)) : sb.Append("' , '")
            sb.Append(eng(i, j, 2)) : sb.Append("' , '")
            sb.Append(eng(i, j, 3)) : sb.Append("' , '")
            sb.Append(eng(i, j, 4)) : sb.Append("' )")
            cmd1.CommandText = sb.ToString
            cmd1.ExecuteNonQuery()
        Next
        MyConnection.Close()

1 个答案:

答案 0 :(得分:0)

OleDb比自动化更快。 向我们展示您的代码,可能还有其他问题。

[编辑] 如果您真的想使用自动化(因为您希望保持工作簿的打开状态),您可以阅读以下文章:How to transfer data to an Excel workbook by using Visual Basic .NET