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

Dar*_*rdi 9 .net c# excel-interop sql-server-2008 varbinarymax

我正在尝试将Excel文件保存到数据库中,我不想使用文件流,因为它需要有一个服务器.

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

mar*_*c_s 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

要重新检索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);
 }
Run Code Online (Sandbox Code Playgroud)

当然,你可以根据自己的需要调整它 - 你可以做很多其他事情 - 取决于你真正想做的事情(你的问题不是很清楚).