使用VBA在导出的HTML表中添加超链接

时间:2018-08-30 09:38:16

标签: html excel vba

我有一个包含3个列的excel工作表:

GCS_to_BQ = GoogleCloudStorageToBigQueryOperator(
    task_id='gcs_to_bq',
    bucket='test_bucket',
    source_objects_task_id='task-id-of-previos-task',
    destination_project_dataset_table='dest_table',
    schema_object='gs://test-bucket/schema.json',
    source_format='CSV',
    create_disposition='CREATE_IF_NEEDED',
    write_disposition='WRITE_TRUNCATE',
    bigquery_conn_id='bq-conn',
    google_cloud_storage_conn_id='gcp-conn',
    dag=dag
)

我将其导出到JSON文件和带有表的HTML文件中,用户可以在其中查看JSON文件中的项目。这对我来说很好。 现在我被困住了,不知道该如何做最后的改进。

我想要HTML文件中A列的“项目”上的C列具有超链接。 要导出HTML文件,请使用以下代码(可以在某处找到):

    A        B            C
  Item   Description   Hyperlink

有人可以给我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

我相信以下内容将达到您的期望,它将像以前一样创建表,但是在为A列中的表创建单元格时,它将从C列中获取值并将其作为超链接添加到新创建的.html文件:

Sub Test()
    RangeToHtml Range("A2:B100"), "G:\PD\PW\Production webpagefiles\new\Overview_Table.html"
End Sub

Sub RangeToHtml(rng As Range, fileName As String)
    Dim resBeg As String
    resBeg = "<html><head><title>Overview</title><link rel=""stylesheet""  href=""Overview_Table_css.css"" type=""text/css"" media=""all"" /></head><body><table><tr class=""heading""><td>Item</td><td>Description</td></tr>"
    resEnd = "</table></body></html>"
    For i = 1 To rng.Rows.Count
        '---Rows---
        resBeg = resBeg & "<tr>"
        For j = 1 To rng.Columns.Count
            '---Columns---
            If j = 1 Then 'if column 1 = A, then add hyperlink found in column C by offseting by 2 columns
                resBeg = resBeg & "<td><a href=" & rng.Cells(i, j).Offset(0, 2).Value & ">" & rng.Cells(i, j).Value & "</a></td>"
            Else
                resBeg = resBeg & "<td>" & rng.Cells(i, j).Value & "</td>"
            End If
        Next j
        resBeg = resBeg & "</tr>"
    Next i
    Stop
    Call SaveStringToFile(resBeg & resEnd, fileName)
End Sub

Sub SaveStringToFile(str As String, fileName As String)
    Open fileName For Output As #1
    Print #1, str
    Close #1
End Sub