C#读取文件并在表格中显示

时间:2011-06-15 08:21:41

标签: c#

我的目标是阅读文本文件并在表格中显示内容。 我经历了很多论坛和镜头,但仍然无法找到解决方案。

我的表格格式:

<table >

   <`tr>

      <`td>

         Australia

      <`/td>

      <`td>

         <`table>

            <`tr>

               <`td>

                  1

               <`/td>

            <`/tr>

         <`/table>

       <`/tr>

<`/table>

我的TextFile看起来像:

Australia = 1,1,2,2

Malaysia = 1,1,1,2,2,2

Singapore = 1,1,1,1,2,2,2,2

我的阅读代码:

        string path = @"..\TestFile.txt";
        char token = ',';
        char token2 = '=';

        string[] lines = File.ReadAllLines(path);

        Response.Write("<table>");
        foreach (string line in lines)
        {
            string[] country = line.Split(token2);
            string[] image = line.Split(token);
            string row = "<tr><td>" + country + "</td>" +"<table><tr>";
            Response.Write(row);
            for (int i = 0; i < image.Length; i++)
            {   

                string row2 = "<td>" + image[i] +"</td>";
                Response.Write(row2);
            }
            Response.Write("</tr></table>");
        }
        Response.Write("</tr></table>");

我的结果:

System.String[]
Australia = 1   1   2   2
System.String[]
Malaysia = 1    1   1   2   2   2
System.String[]
Singapore = 1   1   1   1   2   2   2   2

以及我想要实现的目标:

Australia    1     1    2    2

Malaysia     1     1    1    2    2    2

Singapore    1     1    1    1    2    2    2    2

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:2)

如果我理解正确的问题,请尝试这样做:

string[] country = line.Split(token2);
string[] image = country[1].Split(token); //<- take string after = symbol, and split it
string row = "<tr><td>" + country[0] + "</td>" +"<table><tr>"; //<- take first string before = symbol

答案 1 :(得分:0)

从快速阅读问题开始,您似乎已经能够分割/解析内容,并且只是想要一种格式化输出的方法。

可以使用String.PadLeft()String.PadRight()来实现。或者String.Format("{0,-10}", stringValue)

HTH,

<强>参考