我需要在Excel单元格字符串中替换所有带有粗体字体的html粗体标记子字符串并删除标记。我想我需要以某种方式遍历字符串,同时删除标签并设置如下字体:
xlWorksheet.Cells(1, 2).characters(a, b).font.bold = True
这应该在Windows Forms,vb.net或c#中完成,而不是VBA。 我知道有一种使用Internet Explorer的方式,但我宁愿不使用它。 任何线索?
答案 0 :(得分:0)
您可以通过多种方式完成自己想要的工作。以下是如何完成您想要做的事情的一个很好的示例。
http://vb.net-informations.com/excel-2007/vb.net_excel_update_data_oledb.htm
Imports System.Data
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim myCommand As New System.Data.OleDb.OleDbCommand
Dim sql As String
MyConnection = New System.Data.OleDb.OleDbConnection _
("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + _
"'c:\testfile.xls';Extended Properties=Excel 8.0;")
MyConnection.Open()
myCommand.Connection = MyConnection
' This would be where you would find the HTMl or strings that you are trying to change.
sql = "Update [Sheet1$] set name = 'New Name' where id=1"
myCommand.CommandText = sql
myCommand.ExecuteNonQuery()
MyConnection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
MsgBox("Updated ")
End Sub
End Class
答案 1 :(得分:0)
行。是我自己做的。这仅适用于粗体标签。
xlWs.Cells(1, 2).value = StripTags("this <b>should</b> be <b>bold</b>")
Dim toBold As String = "this <b>should</b> be <b>bold</b>"
Dim i As Integer = 0
Dim loopcount As Integer = 0
While i > -1
Dim startTag As Integer = toBold.IndexOf("<b>", i)
If startTag = -1 Then Exit While
Dim endTag As Integer = toBold.IndexOf("</b>", i)
toBold.Remove(startTag, 3)
toBold.Remove(endTag, 4)
xlWs.Cells(1, 2).characters(startTag + 1 - (loopcount * 7), endTag - startTag - 3).font.bold = True
loopcount += 1
i = endTag + 1
End While
Function StripTags(ByVal html As String) As String
Return Regex.Replace(html, "<.*?>", "")
End Function