HttpRequest 和 BlobServiceClient 程序集或命名空间的 Azure Function .Net 代码问题

问题描述 投票:0回答:1

我有以下 azure 函数代码来从 Azure blob 存储读取 excel 文件,但它给出了以下 2 个错误。我正在使用 .Net Framework 4.8,并且我还在我的解决方案中添加了 System.net.http 包,现在由于缺乏 .Net 编程方面的专业知识,我不确定如何解决以下两个问题。

我认为问题是因为 HttpRequest 和 BlobServiceClient 都不支持 .Net 4.8 框架。

有人可以帮我解决这个问题吗?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
using OfficeOpenXml; // Install the NuGet package "EPPlus"

public static class ExtractEmailsFromExcel
{
    private static readonly string _storageConnectionString = "connectionstring";
    private static readonly string _blobContainerName = "";
    private static readonly string _excelFileName = "";

    [FunctionName("ExtractEmails")]
    public static async Task<HttpResponseMessage> Run(
        [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        try
        {
            // Download Excel file from Azure Blob Storage
            var emailAddresses = await DownloadAndExtractEmails(_storageConnectionString, _blobContainerName, _excelFileName);

            // Return list of email addresses
            return req.CreateResponse(HttpStatusCode.OK, emailAddresses);
        }
        catch (Exception ex)
        {
            log.LogError($"Error: {ex.Message}");
            return req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
        }
    }

    private static async Task<List<string>> DownloadAndExtractEmails(string storageConnectionString, string containerName, string fileName)
    {
        var emails = new List<string>();

        using (var client = new BlobServiceClient(storageConnectionString))
        {
            var containerClient = client.GetBlobContainerClient(containerName);
            var blobClient = containerClient.GetBlobClient(fileName);

            if (await blobClient.ExistsAsync())
            {
                var downloadStream = await blobClient.DownloadStreamingAsync();
                using (var memoryStream = new MemoryStream())
                {
                    await downloadStream.CopyToAsync(memoryStream);
                    memoryStream.Position = 0;

                    using (var excelPackage = new ExcelPackage(memoryStream))
                    {
                        var worksheet = excelPackage.Workbook.Worksheets.First(); // Assuming first worksheet
                        var emailColumn = 1; // Assuming email addresses are in the first column (index 1)

                        for (int row = 2; row <= worksheet.Dimension.End.Row; row++) // Skip header row (index 1)
                        {
                            var email = worksheet.Cells[row, emailColumn].Value?.ToString()?.Trim();
                            if (!string.IsNullOrEmpty(email))
                            {
                                emails.Add(email);
                            }
                        }
                    }
                }
            }
        }

        return emails;
    }
}

错误-

找不到类型或命名空间名称“HttpRequest”(您是 缺少 using 指令或程序集 参考?)ExcelRead C:\Users\suraj.pardeshi\source epos\ExcelRead\ExcelRead\Function1.cs 行 22

找不到类型或命名空间名称“BlobServiceClient”(是 您缺少 using 指令或程序集 参考?)ExcelRead C:\Users\suraj.pardeshi\source epos\ExcelRead\ExcelRead\Function1.cs 行 46

c# .net azure-functions httprequest
1个回答
0
投票

我对您的代码做了一些修改,并且能够从 Azure Blob 存储读取 excel 文件。

代码片段:

//using ..

using Azure.Storage.Blobs;
using OfficeOpenXml;
using System.Text;

 public static class Function1
 {
     private static readonly string _storageConnectionString = "<Storage_connection_string>";
     private static readonly string _blobContainerName = "containerName";
     private static readonly string _excelFileName = "excelname.xlsx";

     [FunctionName("ExtractEmails")]
     public static async Task<HttpResponseMessage> Run(
         [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequestMessage req,
         ILogger log)
     {
         log.LogInformation("C# HTTP trigger function processed a request.");

         try
         {
             ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

             // Download Excel file from Azure Blob Storage
             var emailAddresses = await DownloadAndExtractEmails(_storageConnectionString, _blobContainerName, _excelFileName);

             // Return list of email addresses
             foreach (var email in emailAddresses)
             {
                 log.LogInformation($"Processing email: {email}");

                 // Process each email address as needed
             }
             return req.CreateResponse(HttpStatusCode.OK, "Email addresses in excel processed successfully");
         }
         catch (Exception ex)
         {
             log.LogError($"Error: {ex.Message}");
             return req.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
         }
     }

     private static async Task<List<string>> DownloadAndExtractEmails(string storageConnectionString, string containerName, string fileName)
     {
         var emails = new List<string>();

         Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

         var client = new BlobServiceClient(storageConnectionString);
         var containerClient = client.GetBlobContainerClient(containerName);
         var blobClient = containerClient.GetBlobClient(fileName);

         if (await blobClient.ExistsAsync())
         {
             var downloadStream = await blobClient.DownloadStreamingAsync();
             using (var memoryStream = new MemoryStream())
             {
                 await downloadStream.Value.Content.CopyToAsync(memoryStream);
                 memoryStream.Position = 0;

                 using (var excelPackage = new ExcelPackage(memoryStream))
                 {
                     var worksheet = excelPackage.Workbook.Worksheets.First(); // Assuming first worksheet
                     var emailColumn = 1; // Assuming email addresses are in the first column (index 1)

                     for (int row = 2; row <= worksheet.Dimension.End.Row; row++) // Skip header row (index 1)
                     {
                         var email = worksheet.Cells[row, emailColumn].Value?.ToString()?.Trim();
                         if (!string.IsNullOrEmpty(email))
                         {
                             emails.Add(email);
                         }
                     }
                 }
             }
         }
         return emails;
     }

.csproj:

<PropertyGroup>
  <TargetFramework>net48</TargetFramework>
  <AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Azure.Storage.Blobs" Version="12.20.0" />
  <PackageReference Include="EPPlus" Version="7.2.1" />
  <PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.39" />
  <PackageReference Include="Microsoft.Azure.WebJobs.Extensions.Http" Version="3.2.0" />
  <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
  <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.4.0" />
  <PackageReference Include="OfficeOpenXml.Core.ExcelPackage" Version="1.0.0" />
  <PackageReference Include="System.Text.Encoding.CodePages" Version="4.0.0" />
</ItemGroup>

local.settings.json:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "<Storage_connection_string>",
    "AzureWebJobsDashboard": "<Storage_connection_string>",
    "AzureStorage": "<Storage_connection_string>",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}
  • 在 Azure Blob 存储容器中上传了 Excel(.xslx) 文件(包含 4 个电子邮件地址作为数据)。

enter image description here

能够读取Excel内容:

控制台输出:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.