I have one question and I'm hoping it's an easy one for you. (Windows Forms Application, C#, Framework 3.5, SQL Server 2008 R2)
I don't know how to open Excel (it is loaded in byte[] type) via OleDB.
So, what have I done: I have uploaded Excel (.xls(x)) file via form, and saved it in a database as varbinary(max). Now I need to read that Excel file via oleDB. I've managed to load that file from database and saved it into byte[] variable. How can I open byte[] in oleDB? When I uploaded file for the first time (before saving it to the database), I've opened it via OleDB with just passing file path. How can I access Excel's data when it is already stored in memory as byte[]?
If you want to read using OleDB, then you have to write the bytes to disk. For example, you could do this:
var filename = System.IO.Path.GetTempFileName();
// Assuming that fileBytes is a byte[] containing what you read from your database
System.IO.File.WriteAllBytes(filename, fileBytes);
var connection = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filename + ";Extended Properties=\"Excel 12.0;HDR=YES\"";
// Do your work on excel
using (System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(connection))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [Sheet1$]";
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
System.Diagnostics.Debug.WriteLine(rdr["ColumnName"]);
}
}
}
conn.Close();
}
//Cleanup
System.IO.File.Delete(filename);
If you don't want to write the file to disk, you could look into using a third party library that can read excel files from a memory stream. Tools like SpreadsheetGear or Aspose are commercial tools that can accomplish this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With