【问题标题】:How do I insert/retrieve Excel files to varbinary(max) column in SQL Server 2008?如何在 SQL Server 2008 中将 Excel 文件插入/检索到 varbinary(max) 列?
【发布时间】:2012-06-24 08:32:24
【问题描述】:

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

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

【问题讨论】:

    标签: c# .net sql-server-2008 excel-interop varbinarymax


    【解决方案1】:

    如果您想直接在 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);
     }
    

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

    【讨论】:

    • 在保存之前压缩文件是否值得?如果文件很大和/或有很多文件,如果可行的话,这可能是有利的。
    • XLSX 无论如何都被压缩了,
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-15
      • 2014-07-29
      • 2010-10-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多