Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open Excel file stored in byte[] via OleDB?

Tags:

c#

excel

byte

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[]?

like image 964
user1999722 Avatar asked Sep 16 '13 22:09

user1999722


1 Answers

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.

like image 59
John Koerner Avatar answered Oct 21 '22 14:10

John Koerner