簡體   English   中英

使用Azure功能自動將Excel保存為CSV

[英]Use Azure Functions to automate saving Excel to CSV

嘗試使用Azure功能自動將Excel文件保存為blob作為CSV,以便我可以在Logic Apps或Azure Data Factory中使用。 我正在尋找使用ExcelDataReader C#庫,我可以將NuGet包下載到我的功能,但之后就被卡住了。

目前看來我卡住了,因為File.Open命令在本地路徑上查找文件,我收到以下錯誤:

使用(var stream = File.Open(filePath,FileMode.Open,FileAccess.Read))

文件名,目錄名或卷標語法不正確:'D:\\ Program Files(x86)\\ SiteExtensions \\ Functions \\ 2.0.12507 \\ 64bit ....'

您有關於通過Azure功能保存XLSX的任何建議嗎?

您不必手動打開流,Azure Functions Binding可以為您執行讀取和寫入操作。

例如:

[FunctionName("ConvertExcelToCSV")]
    public static async Task RunAsync(
        [BlobTrigger("excel-files/{blobName}")] Stream excelFileInput,
        [Blob("csv-files/{blobName}", FileAccess.Write)] Stream csvFileOutput,
        CancellationToken token,
        ILogger log)
    {
        log.LogInformation($"Do your processing on the excelFileInput file here.");
        //Do your processing on another steam. Maybe, MemoryStream
        await memoryStream.CopyToAsync(csvFileOutput, 4096, token);
    }

如果使用Environment.CurrentDirectory來獲取執行目錄,它將響應您顯示的目錄。 而這個目錄在azure kudu中,不允許創建文件,因此你的excel文件不存在。 您可以使用context.FunctionDirectory來獲取當前的函數目錄(例如,在Azure上運行時)

例如:

public static void Run([TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log, ExecutionContext context)
        {
            var excelFilePath = context.FunctionDirectory + @"\Book.xlsx";
            var destinationCsvFilePath = context.FunctionDirectory + @"\test.csv";

            System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

            var stream = new FileStream(excelFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

            IExcelDataReader reader = null;

            reader = ExcelReaderFactory.CreateOpenXmlReader(stream);

            var ds = reader.AsDataSet(new ExcelDataSetConfiguration()
            {
                ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                {
                    UseHeaderRow = false
                }
            });

            var csvContent = string.Empty;
            int row_no = 0;
            while (row_no < ds.Tables[0].Rows.Count)
            {
                var arr = new List<string>();
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                {
                    arr.Add(ds.Tables[0].Rows[row_no][i].ToString());
                }
                row_no++;
                csvContent += string.Join(",", arr) + "\n";
            }
            StreamWriter csv = new StreamWriter(destinationCsvFilePath, false);
            csv.Write(csvContent);
            csv.Close();

            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
        }

只需在此處更新您的Excel:

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM