Azure Logic App Store Excel 电子邮件附件到 Blob,下载并阅读

Azure Logic App Store Excel Email Attachment To Blob, Download and Read

我已经设置了一个 azure logic 应用程序来侦听具有特定标题的电子邮件。该电子邮件有一个 excel 附件。当电子邮件到达时,它会将附件推送到 Azure blob 并将消息放在 queue.

然后我有一个函数应用程序侦听该消息并尝试处理该文件。

我有以下代码将 blob 下载为流:

BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blobClient = containerClient.GetBlobClient(fileName);
BlobDownloadInfo download = await blobClient.DownloadAsync();
using Stream downloadFileStream = new MemoryStream();
await download.Content.CopyToAsync(downloadFileStream);
downloadFileStream.Position = 0;

然后我将其转换为如下所示的 Azure blob object:

public class AzureBlob
{
    public string Id { get; set; }
    public string Name { get; set; }
    public string ContentBytes { get; set; }
    public string ContentType { get; set; }
    public int Size { get; set; }
    public bool IsInline { get; set; }
    public DateTime LastModifiedDateTime { get; set; }
    public string ContentId { get; set; }
}

使用此代码:

StreamReader reader = new StreamReader(downloadFileStream);
string fileContents = reader.ReadToEnd();
AzureBlob blob = JsonSerializer.Deserialize<AzureBlob>(fileContents);

然后我尝试像这样用 OpenXML 打开它:

(“ContentType”返回为“application/vnd。openxmlformats-officedocument。spreadsheetml.sheet”)

Stream stockFileStream = new MemoryStream(Encoding.Unicode.GetBytes(blob.ContentBytes));
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(stockFileStream, true);

但我得到以下错误:

System.IO.FileFormatException: File contains corrupted data.

谁能帮我找出我做错了什么?

我发现blob.ContentBytes是一个base64字符串,你需要用Convert.FromBase64String把它转换成bytes[]。

Stream stockFileStream = new MemoryStream(Convert.FromBase64String(blob.ContentBytes));

通过稍微改变 class 使其工作:

public class AzureBlob
{
    public string Id { get; set; }
    public string Name { get; set; }
    public byte[] ContentBytes { get; set; }
    public string ContentType { get; set; }
    public int Size { get; set; }
    public bool IsInline { get; set; }
    public DateTime LastModifiedDateTime { get; set; }
    public string ContentId { get; set; }
}

并对我的代码稍作改动,将其转换为流:

// get the file
BlobContainerClient containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
BlobClient blobClient = containerClient.GetBlobClient(fileName);
BlobDownloadInfo download = await blobClient.DownloadAsync();
        
// convert the stream to an azure blob object
StreamReader reader = new StreamReader(download.Content);
string fileContents = reader.ReadToEnd();
AzureBlob blob = JsonSerializer.Deserialize<AzureBlob>(fileContents);

// convert the stock file to a stream
Stream stockFileStream = new MemoryStream(blob.ContentBytes);