简体   繁体   English

如何在Azure Logic应用中解析Excel电子表格

[英]How to parse Excel spreadsheets in Azure Logic Apps

I need to parse and extract Column information from an Excel spreadsheet using Azure Logic Apps 我需要使用Azure Logic Apps从Excel电子表格中解析和提取列信息

I have already setup the ability for my Logic App to retrieve the latest unread Emails from my Outlook. 我已经为Logic App设置了从Outlook检索最新的未读电子邮件的功能。 Also, my Logic App does a FOR EACH to read all attachments (from unread emails) and make sure they are Excel files (based on filename extension). 另外,我的Logic App会执行FOR EACH读取所有附件(从未读的电子邮件中读取),并确保它们是Excel文件(基于文件扩展名)。

I have a basic Excel file that contains 3 columns "Product, Description, Price" I need to parse each row (only Product and Price) column. 我有一个基本的Excel文件,其中包含3列“产品,说明,价格”,我需要解析每行(仅产品和价格)列。

I will add the ability to store that parsed into into my SQL table hosted on Azure. 我将添加将解析的内容存储到Azure托管的SQL表中的功能。

I suggest you call an Azure Function from your logic App and use the Function to convert the Excel into a JSON Object. 建议您从逻辑应用程序调用Azure函数,然后使用该函数将Excel转换为JSON对象。 (I am currently doing this very succesfully) I use ExcelDataReader parse to parse a Blob that the Logic App creates. (我目前非常成功地执行了此操作)我使用ExcelDataReader parse来解析Logic App创建的Blob。 Send the blob location in the request and respond back with the JSON. 发送请求中的Blob位置,然后使用JSON进行回复。

Here you go, you could use HTTP Request as well. 在这里,您也可以使用HTTP请求。

在此处输入图片说明

using ExcelDataReader;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Nancy.Json;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace ConvertExcelToJSon
{
    public static class Function1
    {
        [FunctionName("ConvertToJson")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");


            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            string blobName = data?.blobName;

            string[] splitBlob = blobName.Split('/');

            Stream blob = await GetBlobStreamAsync(splitBlob[1], splitBlob[2] + "/" + splitBlob[3]);
            DataSet ds = CreateDataSet(blob);
            List<Simple> simpleList = new List<Simple>();
            foreach (DataTable table in ds.Tables)
            {

                return (ActionResult)new OkObjectResult(DataTableToJSON(table));

            }


            return blobName != null
            ? (ActionResult)new OkObjectResult($"Hello, {blobName}")
            : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }



        public static string DataTableToJSON(DataTable table)
        {
            List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();

            foreach (DataRow row in table.Rows)
            {
                Dictionary<string, object> dict = new Dictionary<string, object>();

                foreach (DataColumn col in table.Columns)
                {
                    dict[col.ColumnName] = (Convert.ToString(row[col]));
                }
                list.Add(dict);
            }
            JavaScriptSerializer serializer = new JavaScriptSerializer();

            return serializer.Serialize(list);
        }

        public static string AppSetting(this string Key)
        {
            string ret = string.Empty;
            if (Environment.GetEnvironmentVariable(Key) != null)
            {
                ret = Environment.GetEnvironmentVariable(Key);
            }
            return ret;
        }

        public static async Task<Stream> GetBlobStreamAsync(string containerName, string blobName)
        {
            Stream myBlob = new MemoryStream();
            if (CloudStorageAccount.TryParse("AzureWebJobsStorage".AppSetting(), out CloudStorageAccount storageAccount))
            {
                CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = cloudBlobClient.GetContainerReference(containerName);
                CloudBlob myBloab = container.GetBlobReference(blobName);
                await myBloab.DownloadToStreamAsync(myBlob);
                myBlob.Seek(0, SeekOrigin.Begin);
            }
            return myBlob;
        }
        public static DataSet CreateDataSet(Stream stream)
        {
            DataSet ds;
            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
            IExcelDataReader reader = null;
            reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
            ds = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = true,
                }
            });
            return ds;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Azure Logic Apps将推文插入excel文件 - How to insert tweets into a excel file using Azure Logic Apps 如何将 SQL 服务器 select 的结果导入 Z3A580FZ03Logic 3022036F63F1 中的新 Excel 文件? - How do I import results of SQL server select into a new Excel file in Azure Logic Apps? 在Windows Phone 8应用中创建和邮寄Excel电子表格 - Creating and mailing Excel spreadsheets in Windows Phone 8 apps 如何解决错误代码:&#39;404&#39;,消息:&#39;使用 azure 逻辑应用程序向 excel 文件添加行时,请求的资源不存在? - How to solve Error code: '404', Message: 'The requested resource doesn't exist when adding a row to an excel file using azure logic apps? 比较两个Excel电子表格时,如何解析每个字符串? - How do I parse every string while comparing two excel spreadsheets? 使用逻辑应用从 sharepoint online 读取 Excel 然后插入到 Azure SQL - Using Logic Apps to read Excel from sharepoint online and then inserting into Azure SQL 如何通过 Azure 逻辑应用程序在共享点创建空白 Excel 文件 - How to create blank excel file at sharepoint through azure logic app 有没有办法将 excel 电子表格解析为 Python 中的 xml(电子表格包含段落和表格)? - Is there a way to parse excel spreadsheets to xml(The spreadsheet contains paragraphs and tables) in Python? 如何在Excel电子表格中识别“ #VALUE!”? - How do I recognize “#VALUE!” in Excel spreadsheets? 如何生成带有嵌入式图形的Excel电子表格? - How to generate Excel spreadsheets with embedded graphs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM