首页 > 解决方案 > 使用 MemoryStream 读取 excel 文件

问题描述

有没有办法MemoryStream在 C# 中简单地读取为 excel 文件?我目前正在使用本机微软库Microsoft.Office.Interop.Excel。有没有办法可以用这个库读取 excel 文件?

打开 Excel 文件

using Microsoft.Office.Interop.Excel; // using this namespace

public ExcelHelper(string path)
{
   _xlApp = new Application();
   _xlWorkbook = _xlApp.Workbooks.Open(path);
}

帮手

public static MemoryStream DownloadFile(FtpHandler handler, FtpDirectoryOrFileDetail detail)
{
    var fileByte = handler
    .Download
    .FileByPath(detail.FilePart.Filename, detail.SubFolderPath + "/", false)?.Data;
    if (fileByte is null) return stream;

    using (var fileStream = new MemoryStream(fileByte))
       return fileStream;

    return null;
}

问题是Open扩展名似乎只使用了一个string参数而没有MemoryStream. 有没有人遇到这个问题并且能够解决这个问题?我对任何建议都持开放态度。

标签: c#excel

解决方案


Below is tested solution which writing Excel workbook to memory stream and returning _objectstream which can be used to write to blob and anywhere else.



 using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
            {
                IWorkbook workbook = new XSSFWorkbook();
                logic goes here......
                
                workbook.Write(obj_stream);
                using (MemoryStream tempStream = new MemoryStream())
                {
                    workbook.Write(tempStream);
                    var byteArray = tempStream.ToArray();
                    stream = new MemoryStream(byteArray);
                    obj_stream = stream;
    
                }
          } 
     return obj_stream    

       

推荐阅读