2017-04-09 1 views
1

私はVS17のコードを書き、そのコードは、(ファイルのパスを読み取り、OLE.DB使用してそれを読み取ることによって、これまでそれを使用した)xlsxファイルに格納されたデータベースを使用するの埋込みXLSXのfileinto:exeファイルのC#

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]}であるということです。

私は実際にその値をセルとしてデータベースとして使用できるパスまたはファイルにすることはできますか?

あなたはバイト配列(byte[])を取得していると、あなたのExcelファイルへのパスとしてそのバイト配列を使用しようとしているライン

var fileString = namespace.Properties.Resources.DataBase; 

+0

一時ファイルに保存しますか? –

答えて

0

ありがとうございました。残念ながら、それは動作しません。ファイル名として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); 
関連する問題