Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

interop

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?

like image 611
Vikram Avatar asked Mar 20 '14 13:03

Vikram


2 Answers

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
like image 125
Piotr J. Avatar answered Sep 28 '22 04:09

Piotr J.


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);
    }
}
like image 45
Chris Ballard Avatar answered Sep 28 '22 05:09

Chris Ballard