创建的文件无效/文件无效

时间:2016-07-21 09:36:40

标签: .net vb.net excel filesystems file-type

我正在用户的桌面上创建一个空白文件(.xlsx),然后我需要打开文件并用数据填充此文件,但在打开文件时我收到错误“文件无效”。我使用下面的代码:

Dim filePath As String = desktopPath & "\Suspense_" & Now.Date.ToString("MMddyy") & ".xlsx"

Dim fs As FileStream = Nothing
fs = File.Create(filePath)
'getting error on below line
xlWorkBook = xlApp.Workbooks.Open(filePath)

文件创建成功后,无法打开。

请建议我做错了什么。

1 个答案:

答案 0 :(得分:0)

创建文件并重命名扩展名并不意味着它是该类型的文件。就像将.png文件重命名为.txt一样,并不意味着它现在是一个文本文件。

创建空白Excel文件:

添加对Microsoft Excel Object Library的引用(您的计算机上已安装的任何版本)

然后使用此代码创建一个空白的xlsx文件:

Private _xlApp As Microsoft.Office.Interop.Excel.Application
Private _xlWSheet As Microsoft.Office.Interop.Excel.Worksheet
Private _xlWBook As Microsoft.Office.Interop.Excel.Workbook

Public Sub CreateNewFile()
    Dim filename As String = "C:\Scratch\Test1.xlsx"
    _xlApp = New Microsoft.Office.Interop.Excel.Application
    _xlApp.DisplayAlerts = False
    _xlWBook = _xlApp.Workbooks.Add()
    _xlWBook.SaveAs(filename)
    CloseAndCleanUpExcelObjects()
End Sub

Private Sub CloseAndCleanUpExcelObjects()
    'close the workbook and quit the app
    If _xlWBook IsNot Nothing Then _xlWBook.Close()
    If _xlApp IsNot Nothing Then _xlApp.Quit()
    'destroy the objects
    If _xlWSheet IsNot Nothing Then _xlWSheet = Nothing
    If _xlWBook IsNot Nothing Then _xlWBook = Nothing
    If _xlApp IsNot Nothing Then _xlApp = Nothing

    'Force garbage collection
    GC.Collect()
End Sub