将Microsoft.Office.Interop.Excel.Application转换为byte []

时间:2014-03-20 13:39:11

标签: c# interop

我正在代码中创建一个excel文件,如下面所示

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

现在我想将此excelFile转换为byte []而不保存到硬盘驱动器。怎么可能?

2 个答案:

答案 0 :(得分:3)

前段时间有同样的问题。您必须创建一个临时文件,然后将其读取为字节数组。

示例代码:

            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

答案 1 :(得分:2)

这不是Excel File它是用于Excel Automation的COM对象。它可用于请求Excel将文档保存到磁盘(作为临时文件),然后可以将其加载到byte[]然后删除临时文件。

以下代码可用于为活动工作簿执行此操作:

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