【问题标题】:Importing a space delimited file into a DataGridView将空格分隔文件导入 DataGridView
【发布时间】:2015-01-29 20:29:42
【问题描述】:

我希望将以下数据导入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;
}

数据很好,但只有一列,如何更改定义列宽?

【问题讨论】:

  • 您的示例数据似乎缺少某些字段(公司名称和机器代码)。输入数据是否不一致(即有时缺少字段),还是始终采用以下格式:last upload / size / file name
  • 对不起,我不应该把它们留在里面,它们会被其他方法填充。数据纯粹是“日期/时间”、“字节”和“文件名”。

标签: c# text delimited


【解决方案1】:

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

当你拆分字符串时

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

【讨论】:

    【解决方案2】:

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

    它还自动处理尾随/结束空格。请记住,您必须指定 '\t'' ' 作为分隔符。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多