簡體   English   中英

將XLSX文件嵌入到exe C#中

[英]Embeding XLSX file into exe C#

我在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]}

我如何使它成為一個路徑或文件,我可以實際使用它作為數據庫的單元格中的值?

謝謝

隨着線

var fileString = namespace.Properties.Resources.DataBase;

你得到字節數組( byte[] ),你正在嘗試使用該字節數組作為excel文件的路徑。 不幸的是,這不起作用。 將fileString指定為filename時,你得到那個byte[] .ToString() ,因此{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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM