2012-06-24 7 views

答えて

15

、あなたはこれらの2つの方法を使用することができますバックExcelシートを取得し、ファイルに保存し、このメソッドを使用します。

もちろん
public void RetrieveExcelFromDatabase(int ID, string excelFileName) 
{ 
    byte[] excelContents; 

    string selectStmt = "SELECT BinaryContent FROM dbo.YourTableHere WHERE ID = @ID"; 

    using (SqlConnection connection = new SqlConnection("your-connection-string-here")) 
    using (SqlCommand cmdSelect = new SqlCommand(selectStmt, connection)) 
    { 
     cmdSelect.Parameters.Add("@ID", SqlDbType.Int).Value = ID; 

     connection.Open(); 
     excelContents = (byte[])cmdSelect.ExecuteScalar(); 
     connection.Close(); 
    } 

    File.WriteAllBytes(excelFileName, excelContents); 
} 

、あなたのニーズにこれを適応することができます - あなたも、他のものの多くを行うことができます - あなたが本当に欲しいものに応じて、あなたの質問からあまり明確ではありません。

+0

保存する前にファイルを圧縮することは有益でしょうか?ファイルが大きく、かつ/またはそれらのファイルが多数ある場合は、実行可能であれば、これは有利かもしれません。 –

+0

XLSXはとにかく圧縮されていますが、 –

0

これは、使用しているデータアクセス技術によって異なります。たとえば、Entity Frameworkを使用する場合は、オブジェクトを使用してバイト配列をデータベースに保存するだけです。

// store Excel sheet (or any file for that matter) into a SQL Server table 
public void StoreExcelToDatabase(string excelFileName) 
{ 
    // if file doesn't exist --> terminate (you might want to show a message box or something) 
    if (!File.Exists(excelFileName)) 
    { 
     return; 
    } 

    // get all the bytes of the file into memory 
    byte[] excelContents = File.ReadAllBytes(excelFileName); 

    // define SQL statement to use 
    string insertStmt = "INSERT INTO dbo.YourTable(FileName, BinaryContent) VALUES(@FileName, @BinaryContent)"; 

    // set up connection and command to do INSERT 
    using (SqlConnection connection = new SqlConnection("your-connection-string-here")) 
    using (SqlCommand cmdInsert = new SqlCommand(insertStmt, connection)) 
    { 
     cmdInsert.Parameters.Add("@FileName", SqlDbType.VarChar, 500).Value = excelFileName; 
     cmdInsert.Parameters.Add("@BinaryContent", SqlDbType.VarBinary, int.MaxValue).Value = excelContents; 

     // open connection, execute SQL statement, close connection again 
     connection.Open(); 
     cmdInsert.ExecuteNonQuery(); 
     connection.Close(); 
    } 
} 

へ:あなたはまっすぐADO.NETでそれをやりたい、と彼らはメモリに収まることができるように、あなたのExcelファイルを一度に大きすぎない場合

関連する問題