将空格分隔文件导入DataGridView

时间:2015-01-29 20:29:42

标签: c# text delimited

我希望将以下数据导入DataGridView

01-29-15  04:04AM            505758360 examplefilename1.zip
01-28-15  12:28AM            501657000 this_is_another_file.zip
01-29-15  02:27AM           1629952132 random.data.for.example.zip

此数据不是由字符或特定数量的字符或任何字符分隔。我需要将此数据导入DataGridView,我有以下代码:

public void LoadDataToGrid(string pProfile)
{
    string[] lvTextData = File.ReadAllLines(Global.lvPath + @"\" + pProfile + ".txt");

    DataTable dtTextData = new DataTable();

    dtTextData.Columns.Add("Company Name", typeof(string));
    dtTextData.Columns.Add("Size", typeof(string));
    dtTextData.Columns.Add("File Name", typeof(string));
    dtTextData.Columns.Add("Last Upload", typeof(string));

    for(int i=1; i < lvTextData.Length; i++)
        dtTextData.Rows.Add(lvTextData[i].Split());

    grdData.DataSource = dtTextData;
}

数据很好但只位于一列,我该如何更改定义列宽?

2 个答案:

答案 0 :(得分:0)

您的代码(以及您提供的数据)似乎存在一些问题:

分割字符串时

01-29-15  04:04AM            505758360 examplefilename1.zip

它将它拆分为Length == 16的字符串数组(因为它会拆分所有空白字符)。但是你只提供了4列。因此,您希望将16个字符串的数组放入4列中,这显然无法完成。

一件简单的事情是:删除输入字符串Regex.Replace(s, "\\s+, " ");的冗余空格。 (您也可以使用正则表达式解析字符串并将其拆分为组)。然后你可以用空格分割你的字符串,你将获得Length == 4的字符串数组

对于您的示例(尽管您的输入数据显然与列的名称不对应):

 for (int i = 1; i < lvTextData.Length; i++)
 {
     // removes redundant whitespaces
     string removedWhitespaces = Regex.Replace(lvTextData[i], "\\s+", " ");
     // splits the string
     string[] splitArray = removedWhitespaces.Split(' ');
     // [0]: 01-29-15
     // [1]: 04:04AM
     // [2]: 505758360
     // [3]: examplefilename1.zip

     // do some kind of length checking here
     if(splitArray.Length == dtTextData.Columns.Count) 
     { 
         dtTextData.Rows.Add(splitArray);
     }
 }

答案 1 :(得分:0)

您甚至可以查找CSV Reader - 如果您使用的是NuGet,请here

它自动处理尾随/结束空格。请注意,您必须指定&#39; \ t&#39; &#39; &#39; 作为分隔符。

void ReadAndBindCsv()
{
   // open the file "data.csv" which is a CSV file with headers
   using (CsvReader csv = new CsvReader(
                       new StreamReader("data.csv"), true))
   {
        csv.TrimSpaces = true;
        grdData.DataSource = csv;
   }
}