【问题标题】:FIle created is not valid/Invalid file创建的文件无效/文件无效
【发布时间】:2016-07-21 09:36:40
【问题描述】:

我正在用户桌面上创建一个空白文件(.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)

文件创建成功,打开失败。

请指出我做错了什么。

【问题讨论】:

  • 仅仅创建一个扩展名为 XLSX 的文件并不意味着您创建了一个有效的 Excel 文件。您需要使用 Excel 本身(互操作库)或一些知道如何格式化空 Excel 文件的第三方库(EPPlus)

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


【解决方案1】:

创建文件并重命名扩展名并不意味着它是该类型的文件。就像将 .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

【讨论】:

  • 感谢代码!!我之前也使用过参考,但仍然在 xlWorkSheet.Cells(1, "C") = "2" 分配值时遇到错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 2011-05-07
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2019-08-07
  • 2014-11-23
相关资源
最近更新 更多