将数据从HTML表导入C#中的DataTable [英] Import data from HTML table to DataTable in C#

查看:604
本文介绍了将数据从HTML表导入C#中的DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从HTML表格导入一些数据(这里是链接 http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html ),并在我的Form应用程序中显示DataGridView中的前16位人员。从我读过的最好的方法是使用HTML敏捷包,所以我下载了它并包含到我的项目中。我明白要做的第一件事就是加载html文件的内容。这是我用来这样做的代码:

  string htmlCode =; 
using(WebClient client = new WebClient())
{
client.Headers.Add(HttpRequestHeader.UserAgent,AvoidError);
htmlCode = client.DownloadString(http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html);
}
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

doc.LoadHtml(htmlCode);

然后我被卡住了。我不知道如何用html表格中的数据填充我的数据表。我尝试了很多种解决方案,但似乎没有任何工作正常。如果有人可以帮我解决这个问题,我会很高兴。

新的HtmlDocument();
doc.LoadHtml(htmlCode);
var headers = doc.DocumentNode.SelectNodes(// tr / th);
DataTable table = new DataTable();
foreach(头文件中的HtmlNode头文件)
table.Columns.Add(header.InnerText); //从th
创建列//选择带有td元素的行
foreach(doc.DocumentNode.SelectNodes(// tr [td]))
table.Rows中的var行。 Add(row.SelectNodes(td)。Select(td => td.InnerText).ToArray());

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


I wanted to import some data from HTML table (here is a link http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html) and display first 16 people in DataGridView in my Form application. From what I've read the best way to do it is to use HTML Agility pack, so I downloaded it and included to my project. I understand that the first thing to do is to load the content of html file. This is the code I used to do so:

        string htmlCode = "";
        using (WebClient client = new WebClient())
        {
            client.Headers.Add(HttpRequestHeader.UserAgent, "AvoidError");
            htmlCode = client.DownloadString("http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html");
        }
        HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();

        doc.LoadHtml(htmlCode);

And then I got stuck. I don't know how to fill my datatable with data from the html table. I've tried many various solutions but nothing seems to work properly. I'd be glad if anyone could help me with that.

解决方案

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

You'll need the HTML Agility Pack library to use this code.

这篇关于将数据从HTML表导入C#中的DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆