使用 C# 从 Windows 窗体应用程序上的 CSV 文件读取和显示数据

Yas*_*iya 3 c# csv datagridview winforms

我编写了以下用于从 .csv 文件读取数据的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace CSVRead
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void buttonRead_Click(object sender, EventArgs e)
        {
            DataTable dataTable = new DataTable();
            dataTable.Columns.Add("Username");
            dataTable.Columns.Add("Password");
            dataTable.Columns.Add("MachineID");
            string filePath = textBox1.Text;
            StreamReader streamReader = new StreamReader(filePath);
            string[] totalData = new string[File.ReadAllLines(filePath).Length];
            totalData = streamReader.ReadLine().Split(',');
            while (!streamReader.EndOfStream)
            {
                totalData = streamReader.ReadLine().Split(',');
                dataTable.Rows.Add(totalData[0], totalData[1], totalData[2]);
            }
            dataGridView1.DataSource = dataTable;
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的 CSV 文件数据 (readCSV.csv):

Username, Password, MachineID
abc, abc, 123
jkl, jkl, 789
rst, rst, 456
Run Code Online (Sandbox Code Playgroud)

我有一个的dataGridView在我的Windows窗体应用程序(见下文,因为我还没有积累足够的声誉张贴图片图像链接),并希望在此网格视图中显示CSV文件中的数据。这段代码没有抛出任何错误/警告,但它只是没有按照它应该的方式执行。单击“查找”按钮时,数据未显示在dataGridView 中。我正在使用 Visual Studio 2013 专业版。

应用程序

傻我:哎呀!!!上面的代码工作得很好......我在远程机器上编写代码,并将文件存储在本地机器上。此外,按钮单击事件的名称输入错误。

注意: 答案已被标记为已接受,因为它的逻辑也有效。上面写在我的问题中的代码也是一个很好的工作

Moh*_*Ali 5

这是解决您的问题的工作示例。但在开始之前,您在阅读 CVS 文件或 Excel 文件时应该了解一些事情。对于 excel 文件,第一行总是列的名称,因此您不需要手动将列添加到数据表

 try
            {
                // your code here 
     string CSVFilePathName = @"path and file name";
                string[] Lines = File.ReadAllLines(CSVFilePathName);
                string[] Fields;
                Fields = Lines[0].Split(new char[] { ',' });
                int Cols = Fields.GetLength(0);
                DataTable dt = new DataTable();
                //1st row must be column names; force lower case to ensure matching later on.
                for (int i = 0; i < Cols; i++)
                    dt.Columns.Add(Fields[i].ToLower(), typeof(string));
                DataRow Row;
                for (int i = 1; i < Lines.GetLength(0); i++)
                {
                    Fields = Lines[i].Split(new char[] { ',' });
                    Row = dt.NewRow();
                    for (int f = 0; f < Cols; f++)
                        Row[f] = Fields[f];
                    dt.Rows.Add(Row);
                }
                dataGridClients.DataSource = dt;  
 }
            catch (Exception ex )
            {
                MessageBox.Show("Error is " + ex.ToString());
                throw;
            }
Run Code Online (Sandbox Code Playgroud)