创建Excel文件时出错

时间:2015-07-03 01:26:30

标签: vb.net excel

我正在使用vb.net创建excel文件,但它给我一个错误,因为文件格式或文件扩展名文件无效,因此无法打开文件。

    Dim excelLocation As String = txtLocate.Text + txtFilename.Text.Trim + ".xlsx"
    Dim source1 As New BindingSource
    Dim APP As New Excel.Application
    Dim worksheet As Excel.Worksheet
    Dim workbook As Excel.Workbook


    If System.IO.File.Exists(excelLocation) = False Then
        System.IO.File.Create(excelLocation).Dispose()
    End If


    workbook = APP.Workbooks.Open(excelLocation)
    worksheet = workbook.Worksheets("sheet1")
    Dim columnsCount As Integer = dgvList.Columns.Count
    For Each column In dgvList.Columns
        worksheet.Cells(1, column.Index + 1).Value = column.Name
    Next

    For i As Integer = 0 To dgvList.Rows.Count - 1
        Dim columnIndex As Integer = 0
        Do Until columnIndex = columnsCount
            worksheet.Cells(i + 2, columnIndex + 1).Value = dgvList.Item(columnIndex, i).Value.ToString
            columnIndex += 1
        Loop
    Next
    workbook.SaveAs()
    workbook.Close()
    MsgBox("Save!")

0 个答案:

没有答案