使用 Azure Functions 自动保存 Excel 到 CSV

Use Azure Functions to automate saving Excel to CSV

尝试使用 Azure Functions 自动将 Excel 文件作为 CSV 保存到 blob,以便我可以在逻辑应用程序或 Azure 数据工厂中使用。我想使用 ExcelDataReader C# 库,我可以将 NuGet 包下载到我的函数中,但之后就卡住了。

目前看来我被卡住了,因为 File.Open 命令在本地路径查找文件并且我收到以下错误:

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

文件名、目录名或卷标语法不正确:'D:\Program Files (x86)\SiteExtensions\Functions.0.12507bit....'

你们对通过 Azure Functions 保存 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: