如何在 SQL Server 2008 中将 Excel 文件插入/检索到变量二进制(最大)列



>我正在尝试将Excel文件保存到数据库中,我不想使用文件流,因为它需要为此配备服务器。

那么如何在具有 varbinary(max) 类型的列的表中插入/更新/选择呢?

如果您想直接

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

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

这取决于您使用的数据访问技术。例如,如果使用实体框架,则只需使用对象将字节数组保存到数据库中。

最新更新