【问题标题】:Azure Function reading excel (xlsx) fileAzure 函数读取 excel (xlsx) 文件
【发布时间】:2020-03-02 21:42:57
【问题描述】:

我必须将 excel 文件导入 Azure SQL。这是相当频繁的活动,因此不能使用向导或手动过程。该文件包含 8000 行和 95 列。我正在考虑使用 Azure Functions,但使用 openxml 读取 excel 需要花费太多时间(本地晚上)。除了 openxml 和优化下面的代码,我还有其他选择吗?

代码:

using (SpreadsheetDocument workbook =
                         SpreadsheetDocument.Open(uploadedFile, false))
{
    var sheet = ExcelUtilities.GetFirstSheet(workbook);
    var workSheet = sheet.Worksheet;
    var sheetData = workSheet.GetFirstChild<SheetData>();
    IEnumerable<Row> rows = sheetData.Descendants<Row>();

    foreach (Cell cell in rows.ElementAt(0))
    {
        dt.Columns.Add(ExcelUtilities.GetCellValue(workbook, cell));
    }

    for (int rowIndex = 1; rowIndex < rows.Count(); rowIndex++)
    {
        var row = rows.ElementAt(rowIndex);
        DataRow tempRow = dt.NewRow();

        for (int i = 0; i < row.Descendants<Cell>().Count(); i++)
        {
            tempRow[i] = ExcelUtilities.GetCellValue(workbook, row.Descendants<Cell>().ElementAt(i));
        }

        dt.Rows.Add(tempRow);
    }
}

约束

【问题讨论】:

    标签: excel azure-sql-database azure-functions


    【解决方案1】:

    如果您可以将该 Excel 文件放入/上传到存储帐户,则可以在 Azure SQL 数据库上使用 BULK INSERT。

    以下示例使用指向 Azure 存储帐户中的容器(名为 week3)的外部数据源。

    CREATE EXTERNAL DATA SOURCE MyAzureInvoicesContainer
        WITH (
            TYPE = BLOB_STORAGE,
            LOCATION = 'https://newinvoices.blob.core.windows.net/week3',
            CREDENTIAL = UploadInvoices
        );
    

    使用 BULK INSERT,不要在文件描述中使用容器名称:

    BULK INSERT Colors2
    FROM 'inv-2017-01-19.csv'
    WITH (DATA_SOURCE = 'MyAzureInvoicesContainer',
          FORMAT = 'CSV');
    

    如果您仍想为此任务使用 Azure 函数,here 您将找到完整示例。

    【讨论】:

    • CSV 是一种 Excel 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多