使用Azure函数自动将Excel保存到CSV

时间:2019-06-11 22:39:29

标签: c# azure azure-functions azure-data-factory azure-logic-apps

尝试使用Azure Functions自动将Excel文件保存为CSV格式的Blob,以便可以在Logic Apps或Azure Data Factory中使用。我希望使用ExcelDataReader C#库,但我可以将NuGet包下载到我的Function中,但是之后被卡住了。

当前似乎卡住了,因为File.Open命令在本地路径中查找文件,并且出现以下错误:

使用(可变流= File.Open(filePath,FileMode.Open,FileAccess.Read))

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

关于通过Azure Functions保存XLSX的任何建议吗?

2 个答案:

答案 0 :(得分:3)

您不必手动打开流,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);
    }

答案 1 :(得分:0)

如果使用Environment.CurrentDirectory获取执行目录,它将响应您显示的目录。而且这个目录位于天蓝色的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:

enter image description here