在Resources中读取和写入Excel文件

时间:2016-11-06 14:13:19

标签: excel vb.net

我已将我的Excel文件作为资源添加到我的vb项目中,并使用了"嵌入式资源"选项。文件的名称" StoredInformation.xlsx"。 '构建行动'设置为“嵌入式资源”。

编辑II - 但是我再次陷入困境。好像我的代码在我运行程序时甚至无法正常工作

Dim sPath As String

    sPath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments))

    For i = 1 To 50
        Threading.Thread.Sleep(100)
        Application.DoEvents()

    Next

    If My.Computer.FileSystem.FileExists(sPath & "\Housing\Stored Information.xlsx") Then
        Dim APP As New Excel.Application
        workbook = APP.Workbooks.Open(sPath & "\Housing\Stored Information.xlsx")
        worksheet = workbook.Worksheets("Sheet1")
        APP.Visible = False
        MessageBox.Show("File Opened!" & Environment.NewLine & "Path: " & sPath & "\Housing\Stored Information.xlsx")
    Else
        My.Computer.FileSystem.WriteAllBytes(sPath & "\Housing\Stored Information.xlsx", My.Resources.StoredInformation, True)
        Dim APP As New Excel.Application
        workbook = APP.Workbooks.Open(sPath & "\Housing\Stored Information.xlsx")
        worksheet = workbook.Worksheets("Sheet1")
        APP.Visible = False
        MessageBox.Show("File Created!" & Environment.NewLine & "Path: " & sPath & "\Housing\Stored Information.xlsx")
    End If

它没有创建我的文件夹" Housing"或我的文件"存储的信息.xlsx" 有人可以看看,告诉我我做错了什么?

编辑 - 我发现由于保护级别它无法创建新目录,因此当我将目标更改为桌面时,它创建了excel文件,但需要进行修复。

有人可以告诉我如何在不损坏excel文件的情况下创建新文件夹并添加文件吗?

编辑 - 对代码进行了更改,但仍未在“我的文档”中创建新文件夹并添加文件"存储的信息.xlsx"

2 个答案:

答案 0 :(得分:0)

对于读取和写入excel文件,我会查看我发现的这篇旧帖子,其中列出了一些用于与excel文件交互的库和资源。

Excel Library

More Excel Libraries

答案 1 :(得分:0)

Unraveling the confusion about Embedded Resources - 找到了这个帖子

说明如何嵌入您用于程序的资源以及如何访问它。它确实帮助了我

编辑:回答

Dim sPath As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Housing")

    Dim Fpath As String = sPath & "\Stored Information.xlsx"

    IO.Directory.CreateDirectory(sPath) ' If location already exists it will not do anything

    If My.Computer.FileSystem.FileExists(Fpath) = False Then
       My.Computer.FileSystem.WriteAllBytes(Fpath, My.Resources.StoredInformation, True) ' Don't want to append data (although that would not happen in this instance) so True is used for that.
    End If

    Dim APP As New Excel.Application
    workbook = APP.Workbooks.Open(Fpath)
    worksheet = workbook.Worksheets("Sheet1")
    APP.Visible = False
    MessageBox.Show("File Opened!" & Environment.NewLine & "Path: " & Fpath)