How to manipulate an excel workbook with Excel.Wor

2019-09-15 00:28发布

So, I can't find any methods with file opening in Excel.Workbook or Excel.Application, and I am wondering why.

I have path to an Excel file, and I would like to manipulate it. I understand I have to use Excel.Application, Excel.Workbook, and Excel.Worksheet. The file to the Excel file is ExcelFilePath, what should I do to make it possible?

标签: vb.net excel
2条回答
祖国的老花朵
2楼-- · 2019-09-15 00:46

You first need to add the reference to Microsoft.Office.Interop.Excel to your project in order to use the Excel API, then fill the variables:

Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWS As Excel.Worksheet

xlApp = New Excel.ApplicationClass
xlWorkBook = xlApp.Workbooks.Open(sFilePath)
xlWS = CType(xlWorkBook.Worksheets(sheetNameOrIndex), Excel.Worksheet)

And then you only need to use the methods they have. For example:

Dim sVar as String = xlWS.Range("C5").Value.ToString()
查看更多
孤傲高冷的网名
3楼-- · 2019-09-15 00:53

Try this: from my project

Dim xapp As New Microsoft.Office.Interop.Excel.Application
    Dim wb As Workbook = xapp.Workbooks.Add
    Dim ws As Worksheet = wb.Worksheets(1)
    ws.Activate()

    'Fill header of the sheet----------------------------------
    For i As Integer = 1 To dgvcustomer.Columns.Count
        ws.Cells(1, i) = dgvcustomer.Columns(i - 1).HeaderText
    Next
    'End header------------------------------------------------

    Dim Dgrow, Dgcell, Dgcol As Integer
    Dgrow = 1
    Dgcell = 1

    'Fill Sheet ------------------------------------------------------------------------------------------------

    While (Dgrow <= dgvcustomer.Rows.Count)
        Dgcol = 1
        While (Dgcol <= ws.UsedRange.Columns().Count)
            ws.Cells(Dgrow + 1, Dgcol).value = dgvcustomer.Rows(Dgrow - 1).Cells(ws.Cells(1, Dgcol).value).Value
            Dgcol += 1
        End While
        Dgrow += 1
    End While

    'End fill sheet---------------------------------------------------------------------------------------------

    wb.SaveAs(dlgSaveFile.FileName)
    wb.Close()
    xapp.Quit()
查看更多
登录 后发表回答