Texto HTML con etiquetas a texto formateado en una celda de Excel
¿ Hay una manera de tomar HTML e importarlo a excel para que se formatee como texto enriquecido (preferiblemente usando VBA)? Básicamente, cuando pego en una celda de Excel, estoy buscando convertir esto:
<html><p>This is a test. Will this text be <b>bold</b> or <i>italic</i></p></html>
En esto:
Esto es una prueba. Será este texto negrita o cursiva
6 answers
Sí, es posible:) De hecho, deje que Internet Explorer haga el trabajo sucio por usted;)
PROBADO
MIS SUPOSICIONES
- Estoy asumiendo que el texto html está en la celda A1 de Sheet1. También puede usar una variable en su lugar.
- Si tiene una columna llena de valores html, simplemente ponga el siguiente código en un bucle
CÓDIGO
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("A1").Value
.document.body.createtextrange.execCommand "Copy"
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("A1")
.Quit
End With
End Sub
INSTANTÁNEA
HTH
Sid
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-03 21:15:11
Puede copiar el código HTML al portapapeles y pegarlo de nuevo como texto Unicode. Excel renderizará el HTML en la celda. Echa un vistazo a este post http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii /
El código macro relevante del post:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim objData As DataObject
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
If LCase(Left(Target.Text, 6)) = "<html>" Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
sSelAdd = Selection.Address
Target.Select
Me.PasteSpecial "Unicode Text"
Me.Range(sSelAdd).Select
End If
End If
Application.EnableEvents = True
End Sub
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-25 09:19:50
Si el ejemplo IE no funciona, use este. De todos modos esto debería ser más rápido que empezar hasta una instancia de IE.
Aquí es una solución completa basada en
http://www.dailydoseofexcel.com/archives/2005/02/23/html-in-cells-ii/
Tenga en cuenta, si su innerHTML es todos los números, por ejemplo, '12345', formato HTML ¿no funciona completamente en Excel, ya que trata el número de manera diferente? pero añadir un carácter eg un espacio final al final, por ejemplo. 12345 + formatos" & nbsp; " ok.
Sub test()
Cells(1, 1).Value = "<HTML>1<font color=blue>a</font>" & _
"23<font color=red>4</font></HTML>"
Dim rng As Range
Set rng = ActiveSheet.Cells(1, 1)
Worksheet_Change rng, ActiveSheet
End Sub
Private Sub Worksheet_Change(ByVal Target As Range, ByVal sht As Worksheet)
Dim objData As DataObject ' Set a reference to MS Forms 2.0
Dim sHTML As String
Dim sSelAdd As String
Application.EnableEvents = False
If Target.Cells.Count = 1 Then
Set objData = New DataObject
sHTML = Target.Text
objData.SetText sHTML
objData.PutInClipboard
Target.Select
sht.PasteSpecial Format:="Unicode Text"
End If
Application.EnableEvents = True
End Sub
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-19 07:23:02
Sé que este hilo es antiguo, pero después de asignar el innerHTML, ExecWB trabajó para mí:
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
Y luego simplemente pegue el contenido en Excel. Dado que estos métodos son propensos a errores de tiempo de ejecución, pero funcionan bien después de uno o dos intentos en el modo de depuración, es posible que tenga que decirle a Excel que lo intente de nuevo si se encuentra con un error. Resolví esto agregando este manejador de errores al sub, y funciona bien:
Sub ApplyHTML()
On Error GoTo ErrorHandler
...
Exit Sub
ErrorHandler:
Resume
'I.e. re-run the line of code that caused the error
Exit Sub
End Sub
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-24 00:45:39
Me encontré con el mismo error que BornToCode identificó por primera vez en los comentarios de la solución original. Al no estar familiarizado con Excel y VBA, me tomó un segundo descubrir cómo implementar la solución de tiQU. Así que lo estoy publicando como una solución "Para Dummies" a continuación
- Primero habilite el modo de desarrollador en Excel: Enlace
- Seleccione la pestaña Desarrollador > Visual Basic
- Haga clic en Ver > Código
- Pegue el código a continuación actualizando las líneas que requieren referencias de celda correcto.
- Haga clic en la flecha Verde de Ejecución o presione F5
Sub Sample()
Dim Ie As Object
Set Ie = CreateObject("InternetExplorer.Application")
With Ie
.Visible = False
.Navigate "about:blank"
.document.body.InnerHTML = Sheets("Sheet1").Range("I2").Value
'update to the cell that contains HTML you want converted
.ExecWB 17, 0
'Select all contents in browser
.ExecWB 12, 2
'Copy them
ActiveSheet.Paste Destination:=Sheets("Sheet1").Range("J2")
'update to cell you want converted HTML pasted in
.Quit
End With
End Sub
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-09 20:46:24
Todos ustedes tienen soluciones válidas, y con un puñado de ellas pueden implementar exactamente esto.
Las herramientas necesarias son expresiones regulares, linq, un motor de búsqueda, vb.net o C# e internet.
Busque "tabla html al conjunto de datos". A continuación, busque "dataset to excel without excel installed".
Creo que con esos términos usted podría ser capaz de poner juntos. ;)
Pero aquí hay algunos de los solución.
Using sr As StreamReader = New StreamReader(fileName, Encoding.UTF8)
result = sr.ReadToEnd()
End Using
result = result.Substring(result.IndexOf("<tab"))
Dim sb As New StringBuilder
sb.AppendLine("<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01 Transitional//EN"" ""http://www.w3.org/TR/html4/loose.dtd"">")
sb.AppendLine("<html>")
sb.AppendLine("<head>")
sb.AppendLine("<meta http-equiv=""Content-Type"" content=""text/html; charset=iso-8859-1" > "")
sb.AppendLine("<title>Title</title>")
sb.AppendLine("</head>")
sb.AppendLine("<body>")
sb.Append(result)
sb.AppendLine("</body>")
sb.AppendLine("</html>")
result = sb.ToString()
File.Move(fileName, System.IO.Path.GetFileNameWithoutExtension(fileName) + ".txt")
Dim ds As DataSet = GetTableAsDataSet.ConvertHTMLTablesToDataSet(result)
If (DataSetToExcel.WriteXLSFile(fileName, ds) = True) Then
Http://www.dotnetfunda.com/articles/show/51/convert-html-tables-to-a-dataset
Http://www.codeproject.com/Tips/313731/How-to-convert-DataSet-to-Excel-workbook-xls-using
En aras de la simplicidad, mi archivo de entrada es una tabla html que se asigna a excel correcto dando la vista correcta. Pero una vista es todo lo que es. así que lo leí en strip off the meta styling crap y lo envolví en html válido lo alimenté para obtener el conjunto de datos y escribir el conjunto de datos fuera. disfrutar.
Creo que la expresión regular podría ayudarte a reunir la otra parte del html...
<table[^>]*>(.*?)</table> == <html[^>]*>(.*?)</html>
Los créditos van a los autores de dicho código. Lo acabo de armar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 23:33:31