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

一世执手 提交于 2019-12-10 22:03:59

问题


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?


回答1:


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



回答2:


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);
    }
}


来源:https://stackoverflow.com/questions/22534745/convert-microsoft-office-interop-excel-application-to-byte

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!