将数据从HTML表导入到C#中的DataTable

前端之家收集整理的这篇文章主要介绍了将数据从HTML表导入到C#中的DataTable前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想从 HTML表中导入一些数据(这里是一个链接 http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html),并在我的表单应用程序中显示DataGridView中的前16个人.从我读到的最好的方法是使用HTML Agility包,所以我下载并包含在我的项目中.我知道首先要做的是加载html文件内容.这是我过去常用的代码
  1. string htmlCode = "";
  2. using (WebClient client = new WebClient())
  3. {
  4. client.Headers.Add(HttpRequestHeader.UserAgent,"AvoidError");
  5. htmlCode = client.DownloadString("http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html");
  6. }
  7. HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
  8.  
  9. doc.LoadHtml(htmlCode);

然后我卡住了.我不知道如何使用html表中的数据填充我的数据表.我尝试了很多不同的解决方案,但似乎没有什么工作正常.如果有人能帮助我,我会很高兴的.

解决方法

  1. HtmlDocument doc = new HtmlDocument();
  2. doc.LoadHtml(htmlCode);
  3. var headers = doc.DocumentNode.SelectNodes("//tr/th");
  4. DataTable table = new DataTable();
  5. foreach (HtmlNode header in headers)
  6. table.Columns.Add(header.InnerText); // create columns from th
  7. // select rows with td elements
  8. foreach (var row in doc.DocumentNode.SelectNodes("//tr[td]"))
  9. table.Rows.Add(row.SelectNodes("td").Select(td => td.InnerText).ToArray());

您需要HTML Agility Pack库才能使用此代码.

猜你在找的HTML相关文章