Vikram
Vikram

Reputation: 1627

Convert Microsoft.Office.Interop.Excel.Application to byte[]

I am creating a excel file in the code as Shown Below

 Microsoft.Office.Interop.Excel.Application excelFile = CreateExcelFile();

now I want to convert this excelFile to byte[] without saving to hard drive. How is it possible?

Upvotes: 5

Views: 13976

Answers (2)

Chris Ballard
Chris Ballard

Reputation: 3769

That isn't an Excel File it is a COM object used for Excel Automation. It can be used to request Excel to save a document to disk (as a temporary file), which you could then load into a byte[] and then delete the temporary file.

The following code could be used to do this for the active workbook:

public byte[] GetActiveWorkbook(Microsoft.Office.Interop.Excel.Application app)
{
    string path = Path.GetTempFileName();
    try
    {
        app.ActiveWorkbook.SaveCopyAs(path);
        return File.ReadAllBytes(path);
    }
    finally
    {
        if(File.Exists(path))
            File.Delete(path);
    }
}

Upvotes: 4

Piotr J.
Piotr J.

Reputation: 146

had the same problem some time ago. You have to create a temporary file, and then read it to a byte array.

Example code:

            string tempPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second + DateTime.Now.Millisecond + "_temp";//date time added to be sure there are no name conflicts
            workbook.SaveAs(tempPath, workbook.FileFormat);//create temporary file from the workbook
            tempPath = workbook.FullName;//name of the file with path and extension
            workbook.Close();    
            byte[] result = File.ReadAllBytes(tempPath);//change to byte[]

            File.Delete(tempPath);//delete temporary file

Upvotes: 6

Related Questions