首页 > 解决方案 > Azure Logic App Store Excel 电子邮件附件到 Blob、下载和阅读

问题描述

我已经设置了一个 Azure 逻辑应用程序,用于侦听具有特定标题的电子邮件。该电子邮件有一个 Excel 附件。当电子邮件到达时,它会将附件推送到 Azure Blob 并将消息放入队列中。

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

我有以下代码将 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 对象:

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:文件包含损坏的数据。

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

标签: c#azure-blob-storageopenxml

解决方案


我发现blob.ContentBytes是一个 base64 字符串,您需要使用Convert.FromBase64String将其转换为字节 []。

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

推荐阅读