简体   繁体   中英

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

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.

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.

emp.upload_file = Path.GetFileName(file.FileName);

emp作为您创建的表对象,文件是HttpPostedFileBase文件

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM