如何将Excel文件插入/检索到SQL Server 2008中的varbinary(max)列?

9
我正在尝试将Excel文件保存到数据库中,但我不想使用filestream,因为需要服务器才能使用。
那么,我该如何插入/更新/选择具有varbinary(max)类型列的表?
2个回答

15

如果要使用纯ADO.NET来完成,并且你的Excel文件不太大以至于可以一次性载入内存中,那么你可以使用以下两种方法:

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

要检索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);
 }

当然,您可以根据自己的需求进行调整 - 您也可以做很多其他事情 - 具体取决于您真正想做什么(从您的问题中不太清楚)。

在保存文件之前进行压缩是否值得?如果文件很大和/或文件数量很多,这可能是有利的,如果可行的话。 - B. Clay Shannon-B. Crow Raven
XLSX 无论如何都是压缩的。 - Alan B

0

这取决于您使用的数据访问技术。例如,如果您使用Entity Framework,可以使用对象将字节数组保存到数据库中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接