vb.net 如何使用 Excel.Workbook 操作 Excel 工作簿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14497641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:00:35  来源:igfitidea点击:

How to manipulate an excel workbook with Excel.Workbook

vb.netexcel

提问by Shane Hsu

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

所以,我找不到任何在Excel.Workbook或 中打开文件的方法Excel.Application,我想知道为什么。

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?

我有一个 Excel 文件的路径,我想操作它。我明白我必须使用Excel.ApplicationExcel.WorkbookExcel.Worksheet。Excel文件的文件是ExcelFilePath,我应该怎么做才能使它成为可能?

回答by SysDragon

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

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)

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

然后你只需要使用他们拥有的方法。例如:

Dim sVar as String = xlWS.Range("C5").Value.ToString()

回答by Arpit

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()