如何使用vb.net

时间:2016-02-04 15:53:37

标签: vb.net excel

我已经在excel的宏中多次完成了这个过程,但这是第一次尝试使用vb.net进行此操作并且无法解决这个问题。我有一个xlsx,其中包含行和列数据。我想将数据传输到我制作的模板,该模板有图表等待数据。数据需要转到sheet2,这个文件是xlsm(只读)。我从vba尝试的任何内容都不适用于vb.net。不同的语法。帮助

到目前为止我的代码:

Imports System
Imports System.IO
Imports System.Text
Imports Excel = Microsoft.Office.Interop.Excel
Imports Office = Microsoft.Office.Core
Public Class Form1
Private Sub cbo_FileList_Click(sender As Object, e As EventArgs) Handles cbo_FileList.Click
    Dim folderpath = "C:\Users\aholiday\Desktop\Data Dump"
    cbo_FileList.Items.Clear()
    For Each file As String In System.IO.Directory.GetFiles(folderpath)
        cbo_FileList.Items.Add(System.IO.Path.GetFileNameWithoutExtension(file))
    Next
End Sub

Private Sub btn_Do_Click(sender As Object, e As EventArgs) Handles btn_Do.Click
    Dim txtpath As String
    Dim csvpath As String = "C:\Temp"
    Dim FileTXT As String
    Dim folderpath As String
    Dim FinalFile As String


    folderpath = "C:\Users\aholiday\Desktop\Data Dump"
    FileTXT = cbo_FileList.Text
    csvpath = "C:\Temp\" & FileTXT & ".csv"
    txtpath = folderpath & "\" & FileTXT & ".txt"
    FinalFile = "C:\Users\aholiday\Desktop\Book1"

    File.Copy(txtpath, csvpath)
    Process.Start("EXCEL.EXE", csvpath)
    Process.Start("EXCEL.EXE", FinalFile)

 'Need to have copy past and close here
    'File.Delete(csvpath)

 End Sub
 End Class  

2 个答案:

答案 0 :(得分:0)

看看EPPlus(你可以通过nuget包管理器获得这个)...这是一个完整的xlsx处理库,对于处理它非常有用。

还有封闭的源库,也可以使用Excel Interop - 但是需要安装Office。

我已经用它来让一些顾客满意

答案 1 :(得分:0)

尝试使用此代码将数据从一个工作簿复制到另一个工作簿:

Public Sub CopyData()

    Dim ExcelApp As New Microsoft.Office.Interop.Excel.Application

    Dim WB1, WB2 As Workbook



    Try

        'optional
        ExcelApp.Visible = False


        'open both workbooks
        WB1 = ExcelApp.Application.Workbooks.Open("C:\...\File1.xlsx")
        WB2 = ExcelApp.Application.Workbooks.Open("C:\...\File2.xlsx")


        'rows
        For r As Integer = 1 To 5

            'columns
            For c As Integer = 1 To 5

                'copy the value of the cell
                WB2.Sheets(2).Cells(r, c).Value = WB1.Sheets(1).Cells(r, c).Value

                'or text:
                'WB2.Sheets(2).Cells(r, c).Text = WB1.Sheets(1).Cells(r, c).Text

            Next

        Next


        'save the second workbook
        WB2.Save()


        'close the workbooks
        WB1.Close()
        WB2.Close()


        'and quit the Excel application
        ExcelApp.Quit()

    Catch ex As Exception

        MessageBox.Show(ex.Message)

        ExcelApp.Quit()

    End Try

End Sub