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

5
我将在代码中创建一个Excel文件,如下所示。
 Microsoft.Office.Interop.Excel.Application excelFile = CreateExcelFile();

现在我想将这个Excel文件转换为字节数组,而不必保存到硬盘上。有什么可能的方法?

可能是 如何在 .NET 中将 Excel 工作簿写入 MemoryStream? 的重复问题。 - Pete Garafano
2个回答

6

我曾经遇到过同样的问题。您需要创建一个临时文件,然后将其读取到一个字节数组中。

示例代码:

            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

如果应用程序具有多会话功能,那么您应该设置一个临时路径:string tempPath = AppDomain.CurrentDomain.BaseDirectory + DateTime.Now.ToString() + Session.SessionID + "_TMP" - Rahnzo

4

这不是一个 Excel 文件,而是用于 Excel 自动化的 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);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接