【发布时间】:2012-06-24 08:32:24
【问题描述】:
我正在尝试将 Excel 文件保存到数据库中,我不想使用文件流,因为它需要一个服务器。
那么,如何在具有varbinary(max) 类型列的表中插入/更新/选择?
【问题讨论】:
标签: c# .net sql-server-2008 excel-interop varbinarymax
我正在尝试将 Excel 文件保存到数据库中,我不想使用文件流,因为它需要一个服务器。
那么,如何在具有varbinary(max) 类型列的表中插入/更新/选择?
【问题讨论】:
标签: c# .net sql-server-2008 excel-interop varbinarymax
如果您想直接在 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);
}
当然,您可以根据自己的需要进行调整 - 您也可以做很多其他事情 - 取决于您真正想做的事情(从您的问题中不是很清楚)。
【讨论】:
这取决于您使用的数据访问技术。例如,如果您使用实体框架,您可以使用对象将字节数组保存到数据库中。
【讨论】: