2012-06-24 70 views

Trả lời

15

Nếu bạn muốn làm điều đó trong ADO.NET thẳng, và các tập tin Excel của bạn không phải là quá lớn để họ có thể phù hợp với bộ nhớ cùng một lúc, bạn có thể sử dụng hai phương pháp:

// 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(); 
    } 
} 

Để lấy tấm Excel lại và lưu nó trong một tập tin, sử dụng phương pháp này:

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); 
} 

Tất nhiên, bạn có thể thích ứng này yêu cầu của bạn - bạn có thể làm được nhiều việc khác nữa - tùy thuộc vào những gì bạn thực sự muốn để làm (không rõ ràng từ câu hỏi của bạn).

+0

Có đáng để nén tệp trước khi lưu không? Nếu các tệp lớn và/hoặc có nhiều tệp, thì điều này có thể thuận lợi, nếu khả thi. –

+0

XLSX vẫn được nén, –

0

Tùy thuộc vào công nghệ truy cập dữ liệu bạn đang sử dụng. Ví dụ, nếu bạn sử dụng Entity Framework, bạn chỉ có thể lưu một mảng byte vào cơ sở dữ liệu bằng cách sử dụng các đối tượng.

Các vấn đề liên quan