-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHtmlCsvConvertor.cs
69 lines (65 loc) · 2.46 KB
/
HtmlCsvConvertor.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using HtmlAgilityPack;
namespace HtmlCsvConvertor
{
public class HtmlCsvConvertor
{
public static string HtmlToCsv(string html, string separator = ";")
{
var document = new HtmlAgilityPack.HtmlDocument();
string CsvResult = string.Empty;
document.LoadHtml(html);
var tables = document.DocumentNode.SelectNodes("//table").ToList();
if (tables.Count == 0)
{
return " ";
}
foreach (var table in tables)
{
if (table.ChildNodes.Any((e) => e.OriginalName == "tbody"))
{
foreach (var node in table.ChildNodes.Where(e => e.OriginalName == "tbody"))
{
foreach (var tr in node.ChildNodes.Where(e => e.OriginalName == "tr"))
{
CsvResult += "\n";
foreach (var td in tr.ChildNodes.Where(e => e.OriginalName == "td"))
{
CsvResult += $"{td.InnerText}{separator}";
}
CsvResult = CsvResult.Substring(0, CsvResult.Length - 1);
}
}
}
else
{
foreach (var tr in table.ChildNodes.Where(e => e.OriginalName == "tr"))
{
CsvResult += "\n";
foreach (var td in tr.ChildNodes.Where(e => e.OriginalName == "td"))
{
CsvResult += $"{td.InnerText}{separator}";
}
CsvResult = CsvResult.Substring(0, CsvResult.Length - 1);
}
}
}
CsvResult = CsvResult.Replace(" ", " ");
return CsvResult;
}
public static string CsvToHtml(string csv, string separator)
{
string html = "<table>";
for (int i = 0; i < csv.Split("\n").Length; i++)
{
html += "<tr>";
for (int j = 0; j < csv.Split("\n")[i].Split(separator).Length; j++)
{
html += $"<td>{csv.Split("\n")[i].Split(separator)[j]}</td>";
}
html += "</tr>";
}
html += "</table>";
return html;
}
}
}