【问题标题】:Embeding XLSX file into exe C#将 XLSX 文件嵌入 exe C#
【发布时间】:2017-09-04 05:43:32
【问题描述】:

我在 VS17 中编写了代码,该代码使用了存储在 xlsx 文件中的数据库(到目前为止,它是通过读取文件的路径并使用 OLE.DB 读取它来使用的):

string DataBase_File = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory.ToString(), String.Format("{0}", db_name));

string constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO""", DataBase_File);
using (OleDbConnection conn = new OleDbConnection(constr))
{
    conn.Open();
    OleDbCommand command = new OleDbCommand(string.Format("Select * from [{0}]", SheetName), conn);
    OleDbDataReader reader = command.ExecuteReader();

当我想将它编译成.exe 文件时,我通过以下方式将该文件添加到资源中:

var fileString = namespace.Properties.Resources.DataBase;

但是,我得到的结果是 fileString 是 {bytes[28432]}

我怎样才能使它成为一个路径或文件,我可以实际使用它单元格中的值作为数据库?

谢谢

【问题讨论】:

  • 保存到临时文件?

标签: c# .net excel embed xlsx


【解决方案1】:

带线

var fileString = namespace.Properties.Resources.DataBase;

您正在获取字节数组 (byte[]),并且您正在尝试使用该字节数组作为您的 excel 文件的路径。不幸的是,这行不通。将 fileString 指定为文件名时,您将获得 .ToString()byte[],因此是 {bytes[28432]}

完成任务的唯一方法是将字节写入(临时)文件,从中获取数据,然后删除临时文件。为此,您可以执行以下操作:

//temp file path
string tempDbPath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
//temp db file name
string tempDbFile = "tempdb.xlsx";
//path + filename
string tempDBLocation = Path.Combine(tempDbPath, tempDbFile);
//get byte array from application's resources
byte[] resourceBytes = Properties.Resources.DataBase;

//write all bytes to specified location
File.WriteAllBytes(tempDBLocation, resourceBytes);

//connect and select data as usual
string constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=NO""", tempDBLocation);
using (OleDbConnection conn = new OleDbConnection(constr))
{
    conn.Open();
    OleDbCommand command = new OleDbCommand(string.Format("Select * from [{0}]", "Sheet1$"), conn);
    OleDbDataReader reader = command.ExecuteReader();
}

//delete temp file
File.Delete(tempDBLocation);

【讨论】:

    猜你喜欢
    • 2020-10-05
    • 2017-06-14
    • 2016-11-08
    • 2013-04-21
    • 1970-01-01
    • 1970-01-01
    • 2019-07-31
    • 2017-12-17
    • 1970-01-01
    相关资源
    最近更新 更多