c# - 将 csv 读取到网格的更快方法

标签 c# .net winforms csv datagridview

我在 Windows Forms .NET 3.5 中有以下内容

对于记录少于 10,000 的 csv,它工作正常,但对于记录超过 30,000 的 csv 则速度较慢。 输入的 csv 文件可以是 1 - 1,00,000 条记录之间的任何记录

目前使用的代码:

/// <summary>
        /// This will import file to the collection object
        /// </summary>
        private bool ImportFile()
        {
            try
            {

                String fName;
                String textLine = string.Empty;
                String[] splitLine;

                // clear the grid view

                accountsDataGridView.Rows.Clear();

                fName = openFileDialog1.FileName;

                if (System.IO.File.Exists(fName))
                {
                    System.IO.StreamReader objReader = new System.IO.StreamReader(fName);

                    do
                    {
                        textLine = objReader.ReadLine();
                        if (textLine != "")
                        {
                            splitLine = textLine.Split(',');
                            if (splitLine[0] != "" || splitLine[1] != "")
                            {
                                accountsDataGridView.Rows.Add(splitLine);
                            }
                        }
                    } while (objReader.Peek() != -1);
                }
                return true;
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("The process cannot access the file"))
                {
                    MessageBox.Show("The file you are importing is open.", "Import Account", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
                else
                {
                    MessageBox.Show(ex.Message);
                }

                return false;
            }

        }

示例输入文件:
18906,Y
18908,Y
18909,Y
18910,Y
18912,N
18913,N

需要一些关于优化此代码以在网格中快速读取和查看的建议。

最佳答案

List<string[]> rows = File.ReadAllLines("Path").Select(x => x.Split(',')).ToList();
DataTable dt = new DataTable();
dt.Columns.Add("1");
dt.Columns.Add("2");
rows.ForEach(x => {
  dt.Rows.Add(x);
});
dgv.DataSource = dt;

试试看,我怀疑你现在在数据网格中有某种形式的列名,我只是将它们设为 1 和 2。

要根据您的原始代码进行过滤,请使用:

List<string[]> rows = File.ReadAllines("Path").Select(x => x.Split(',')).Where(x => x[0] != "" && x[1] != "").ToList();

DataGridView

获取您的列
  dt.Columns.AddRange(dgv.Columns.Cast<DataGridViewColumn>().Select(x => new DataColumn(x.Name)).ToArray());

关于c# - 将 csv 读取到网格的更快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14157153/

相关文章:

c# - Assembly.Load() 名称为 ' ' 的重复类型

c# - 如何正确地从 Web 服务返回值?

c# - 如何禁止在 ToolStripButton 上显示工具提示文本?

.net - 如何将自定义类的通用列表绑定(bind)到 datagridview 并仅在 VB.NET 中显示特定属性?

c# - 可移植类库 - 对类型 'MarshalByRefObject' 的引用声称它在 'mscorlib' 中定义,但找不到

c# - 与 Dropbox 一样,上传后在左下角的文件或文件夹图标上标记正确的符号

c# - 更改 WinForm 按钮文本颜色?

c# - 用于操作文本的小型 Java 或 C# 片段

c# - 在哪些 .NET 语言中,类可以从它自己的嵌套类派生?

c# - C#中如何判断类型是否为字符串?