9

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

0

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't know anything about what library you're using to deal with your Excel data, but the first thing that comes to mind is that it almost certainly has a LoadFromFile method. It might not be called that, but that's what it does. See if it also has a LoadFromStream method, and if so, take your byte[] data and load it into a MemoryStream, and load the XLS from there.

1 Comment

I'm not said person, i would imagine its because you have not done your home work. there are no such methods...
-1
emp.upload_file = Path.GetFileName(file.FileName);

emp as your table object created and file is HttpPostedFileBase file

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.