2012-06-24 13 views

Respuesta

15

Si desea hacerlo en ADO.NET recta, y sus archivos de Excel no son demasiado grandes para que puedan caber en la memoria a la vez, usted podría utilizar estos dos métodos:

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

Para recuperar la hoja de Excel atrás y almacenarlo en un archivo, utilice este método:

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

por supuesto, se puede adaptar esto a sus necesidades - que podría hacer un montón de otras cosas, también - dependiendo de lo que realmente quiere hacer (no muy claro de su pregunta).

+0

¿Valdría la pena comprimir el archivo antes de guardarlo? Si los archivos son grandes y/o hay muchos de ellos, esto podría ser una ventaja, si es factible. –

+0

XLSX está comprimido de todos modos, –

0

Depende de la tecnología de acceso a datos que esté utilizando. Por ejemplo, si usa Entity Framework, puede guardar una matriz de bytes en la base de datos utilizando objetos.

Cuestiones relacionadas