excel - 如何使用 VBA 将 Excel 工作表上传到 Azure ADLS?

标签 excel vba azure azure-blob-storage

我有一个专注于标准化数据集的 VBA 代码,转换完成后,我需要将此 Excel 工作表上传到特定的 ADLS(csv 格式),这样我就能够执行自动化在数据工厂中。我一直在寻找一些指导,但不幸的是我并不幸运,我不知道从哪里开始。

下面是代码(非常简单,代码只需选择工作表并删除一些列):

Sub Delete_Columns()

    Dim k As Integer

    Worksheets("File").Select
    For k = 1 To 4
    Columns(k + 1).Delete
    Next k

End Sub

你能帮我一下吗?为了实现目标,需要在我的代码中添加什么?我是否需要 Blob SAS token 以及如何指定路径?

最佳答案

How to upload an Excel sheet to Azure ADLS by using VBA?

您可以使用下面的代码删除列并使用 VBA 将 Excel 工作表上传到 ADLS 帐户。

在 Visual Basic 编辑器中,转到“插入”>“模块”以创建新模块。将代码复制并粘贴到新模块中。

代码:

Sub Delete_Columns_And_Upload()

    Dim k As Integer
    Dim CSVFilePath As String
    Dim BlobServiceURL As String
    Dim ContainerName As String
    Dim BlobName As String
    Dim SAS_Token As String
    Dim HTTPReq As Object

    Worksheets("File").Select
    For k = 1 To 4
        Columns(k + 1).Delete
    Next k

    ' Specify the local path where you want to save the CSV temporarily
    CSVFilePath = "C:\Users\xxxx\test.csv"

    ' Save the modified sheet as CSV
    ActiveSheet.SaveAs CSVFilePath, xlCSV

    ' Define your Azure ADLS Storage URL
    BlobServiceURL = "https://yourstorageaccountname.blob.core.windows.net/"
    ContainerName = "test"
    BlobName = "example.csv"

    ' Specify your SAS Token here (including the leading '?')
    SAS_Token = "?sv=2022-11-02&ss=bfqt&srt=co&sp=rwdlacupiytfx&se=2023-09-20T13:57:47Z&st=2023-09-20T05:57:47Z&spr=https&sig=xxxxxx"

    ' Combine the URL components
    Dim UploadURL As String
    UploadURL = BlobServiceURL & ContainerName & "/" & BlobName & SAS_Token

    ' Create an HTTP request object
    Set HTTPReq = CreateObject("MSXML2.ServerXMLHTTP.6.0")

    ' Read the CSV file data
    Dim FileData As String
    Open CSVFilePath For Binary As #1
    FileData = Space$(LOF(1))
    Get #1, , FileData
    Close #1

    ' Send a PUT request to upload the file to Azure Blob Storage
    HTTPReq.Open "PUT", UploadURL, False
    HTTPReq.setRequestHeader "Content-Type", "application/octet-stream"
    HTTPReq.setRequestHeader "x-ms-blob-type", "BLockblob"
    HTTPReq.send FileData

End Sub

控制台:

enter image description here

现在,打开宏对话框并选择 Delete_Columns_And_Upload 宏,然后单击运行 运行代码。

输出:

上面的代码使用 VBA 执行并上传了 Excel 文件到 Azure ADLS。

enter image description here

关于excel - 如何使用 VBA 将 Excel 工作表上传到 Azure ADLS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77138731/

相关文章:

azure - Asp 核心 2.2 Azure 事件目录 : Authorization failed

azure - 无法打开 "Multi-Tenant"进行 Azure AD 身份验证

excel - 使用 VBA 在 Excel 中发送电子邮件,没有 Outlook,64 位

python - 创建一个仅提取包含特定单词的行的新数据框

excel - Excel中有没有类似于Ruby的Split方法的函数?

Excel 编程方法

string - 如何从路径中提取文件名?

c# - 我如何使用 c# 在现有的 excel 文件中添加我的 datagridview

vba - 自动用长术语列表的建议替换拼写错误

Azure Windows Server 2016 上的 ASP.NET5 CLR 网站正在运行,但在浏览器中出现 404 NOT FOUND