所以,我找不到在Excel.Workbook
orExcel.Application
中打开文件的任何方法,我想知道为什么。
我有一个 Excel 文件的路径,我想操作它。我知道我必须使用Excel.Application
,Excel.Workbook
和Excel.Worksheet
。Excel文件的文件是ExcelFilePath
,我应该怎么做才能使它成为可能?
您首先需要添加对Microsoft.Office.Interop.Excel
项目的引用才能使用 Excel API,然后填写变量:
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)
然后你只需要使用他们拥有的方法。例如:
Dim sVar as String = xlWS.Range("C5").Value.ToString()
试试这个:从我的项目
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()