所以,我在Excel.Workbook
或Excel.Application
找不到任何文件打开的方法,我想知道为什么。
我有一个Excel文件的路径,我想操纵它。我知道我必须使用Excel.Application
,Excel.Workbook
和Excel.Worksheet
。 Excel文件的文件是ExcelFilePath
,我应该怎么做才能使它成为可能?
答案 0 :(得分:2)
首先需要将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()
答案 1 :(得分:1)
试试这个:从我的项目
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()