如何使用计时器触发器在 azure 函数应用程序中创建 excel 文件

how to create a excel file in azure function App by using timer trigger

我在我的 azure 函数应用程序中创建了一个方法,它从 class 获取静态数据并将其存储到 excel 文件 我正在将 excel 文件存储在存储中帐户。当我 运行 该方法时,会在存储帐户

中创建一个空的 Excel 文件
  1. 如何在 Azure 函数应用程序中创建 Excel 文件

  2. 如何在 Excel 文件中存储数据

    [FunctionName("Function1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log, [Blob("name/empchange.csv", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream myblob, [Blob("name/TestNewExcel.xlsx", FileAccess.Write, Connection = "AzureWebJobsStorage")] TextWriter outputblob)
    {
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    
        try
        {
            // Read CSV File
            ReadCsvFile(myblob);
            // create Excel File
            CreateExcel(outputblob);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
    

Excel方法:

  static void CreateExcel(TextWriter outputblob)
    {
        data clsdata = new data();
        DataTable table = clsdata.Getdata();

        using (SpreadsheetDocument document = SpreadsheetDocument.Create(outputblob.ToString(), SpreadsheetDocumentType.Workbook))
        {
            WorkbookPart workbookPart = document.AddWorkbookPart();
            workbookPart.Workbook = new  Workbook();

            WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            var sheetData = new SheetData();
            worksheetPart.Worksheet = new Worksheet(sheetData);

            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());
            Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet1" };

            sheets.Append(sheet);

            Row headerRow = new Row();

            List<String> columns = new List<string>();
            foreach (DataColumn column in table.Columns)
            {
                columns.Add(column.ColumnName);

                Cell cell = new Cell();
                cell.DataType = CellValues.String;
                cell.CellValue = new CellValue(column.ColumnName);
                headerRow.AppendChild(cell);
            }

            sheetData.AppendChild(headerRow);

            foreach (System.Data.DataRow dsrow in table.Rows)
            {
                Row newRow = new Row();
                foreach (String col in columns)
                {
                    Cell cell = new Cell();
                    cell.DataType = CellValues.String;
                    cell.CellValue = new CellValue(dsrow[col].ToString());
                    newRow.AppendChild(cell);
                }

                sheetData.AppendChild(newRow);
            }
            workbookPart.Workbook.Save();
        }
    }

我的 Azure 函数绑定:

    {
  "bindings": [
    {
      "name": "myblob",
      "type": "blob",
      "path": "name/empchange.csv",
      "direction": "in",
      "connection": "AzureWebJobsStorage"

    },
    {
      "name": "outputblob",
      "type": "blob",
      "path": "name/ExcelFile.xlsx",
      "direction": "out",
      "connection": "AzureWebJobsStorage"

    }
  ],
  "disabled": false
}

如果您想将 csv 文件转换为 excel 文件,我们可以使用包 EPPlus

例如

[FunctionName("Function1")]
        public static async Task Run(
           [TimerTrigger("0 */5 * * * *",RunOnStartup =true)] TimerInfo myTimer,
            [Blob("input/test.csv", FileAccess.ReadWrite, Connection = "AzureWebJobsStorage")] CloudBlockBlob blob,
            [Blob("test/TestNewExcel.xlsx", FileAccess.Write, Connection = "AzureWebJobsStorage")] Stream output,
            ILogger log)
        {
            log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");

            string worksheetsName = "TEST";

            bool firstRowIsHeader = false;
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            var format = new ExcelTextFormat();
            format.Delimiter = ',';
            format.EOL = "\r";
            using (var ms = new MemoryStream()) {
                using (ExcelPackage package = new ExcelPackage(new FileInfo(@"E:\test.xlsx")))
                {

                    string content = await blob.DownloadTextAsync();
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
                    worksheet.Cells["A1"].LoadFromText(content, format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
                    await package.SaveAsAsync(output).ConfigureAwait(false);
                }
                

            }
           
           
        }