2012-06-24 5 views

답변

15

, 당신은이 두 가지 방법을 사용할 수 있습니다 여러분은 여러분의 필요에 이것을 적용 할 수 있습니다, 물론

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에서 그것을하고 싶은, 그들은 메모리에 들어갈 수 있도록 엑셀 파일을 한 번에 너무 큰 수없는 경우