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

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

问题描述

我想从 HTML 表格中导入一些数据(这里有一个链接 http://road2paris.com/wp-content/themes/roadtoparis/api/generated_table_august.html) 并在我的表单应用程序的 DataGridView 中显示前 16 个人.从我读到的最好的方法是使用 HTML Agility 包,所以我下载了它并包含在我的项目中.我知道首先要做的是加载html文件的内容.这是我曾经这样做的代码:

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);

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

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());

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

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

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

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