Search code examples
c#microsoft-graph-apiepplus.net-7.0

EPPlus returns Excel file downloaded from SharePoint without any worksheets


I am using Microsoft Graph to get an excel file from SharePoint, and then I am using EPPlus to convert the IFormFile to an Excel file. This has worked in the past, but we upgraded to .Net 7 recently. Here's what I am using

.Net 7

MS Graph version: 5.39

EPPlus version: 7.0.6

Here is my code for getting the file from SharePoint: (FYI - DAFormFile inheirets from IFormFile)

var fileContent = await _graphServiceClient.Drives[docFolderId].Items[file.Id].Content.GetAsync();
using var ms = new MemoryStream();
await fileContent.CopyToAsync(ms);
var length = ms.Length;
var bob = new MemoryStream(ms.ToArray());

string fileDate = "";

if (myRegex != null)
{
    fileDate = myRegex.Match(file.Name).ToString();
}

DAFormFile formfile = new DAFormFile(
    baseStream: bob,
    baseStreamOffset: ms.Position,
    length: length,
    name: fileDate,
    fileName: file.Name
    )
{
    Headers = new HeaderDictionary(),
    ContentType = file.File.MimeType == mimeTypeXlsm ? "application/vnd.ms-excel.sheet.macroEnabled.12" : "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
};

And here is my code for converting the file to an Excel file:

if (!string.IsNullOrEmpty(password))
{
    //We need to create a read/write memory stream that is needed to read a password protected file
    MemoryStream readWrite = new MemoryStream();
    excelFile.CopyTo(readWrite);
    return new ExcelPackage(readWrite);
}
else
{
    return new ExcelPackage(excelFile.OpenReadStream());
}

The IFormFile object that is produced in the first step has a length to it. However, once the file is converted to an Excel file, there are no worksheets. Can anyone tell me what I'm doing wrong? I have a feeling it's with the IFormFile creation, but I'm not sure.


Solution

  • When you are creating a new instance of DAFormFile you set

    baseStreamOffset: ms.Position
    

    I believe that the current position in the stream (ms.Position) is set to the end of the stream, so it can affect the rest of the code.

    Try to set baseStreamOffset to 0.

    Otherwise we need more details. No idea how do you create excelFile and how did you implement DAFormFile