【问题标题】:how to read CSV and put it into DataGrid view one by one C#如何读取CSV并将其一一放入DataGrid视图C#
【发布时间】:2020-03-16 20:49:23
【问题描述】:

我想在 Excel 上读取 CSV,然后将其一一放入数据库网格中。

比如1小时有200条数据,比如第10分钟可以显示2条数据。然后第 25 分钟有 15 个数据,第 45 分钟有 72 个数据。

以及如何制作它? 请帮帮我

【问题讨论】:

  • 您需要一个后台进程(不同的线程)来定期读取数据。要定期检查数据,可以使用 C# 中的 Timer。如果找到新数据,它将读取数据并将新数据行添加到现有数据列表中并更新数据网格源。
  • 你能给我看一些代码吗? xixixixi

标签: c# winforms csv datagridview


【解决方案1】:

您需要一个后台进程(不同的线程)来定期读取数据。要定期检查数据,可以使用 C# 中的 Timer。

这是 CSV 阅读器:

 public class CSVReader
  {
    string appLocation = System.IO.Directory.GetCurrentDirectory();


    public List<MyDataModel> GetNewCSVValue()
    {
        StreamReader streamReader;
        List<MyDataModel> myDataModels = new List<MyDataModel>();
        MyDataModel myDataModel = null;

        var mydataFile = "../../../UnProcessed/data.csv";

        if (File.Exists(mydataFile))
        {
            try
            {
                streamReader = File.OpenText(mydataFile);

                while (!streamReader.EndOfStream)
                {
                    var valueLine = streamReader.ReadLine();

                    myDataModel = new MyDataModel();

                    var csvValues = valueLine.Split(',');
                    if (csvValues != null)
                    {
                        myDataModel.Column1 = csvValues[0];
                        myDataModel.Column2 = csvValues[1];
                        myDataModels.Add(myDataModel);
                    }

                }

                streamReader.Close();
                streamReader = null;

                // Move the data file to Processed folder
                //File.Move(mydataFile, 
          // "../../../Processed/data"+DateTime.Now.ToString()+".csv");
            }
            catch (Exception ex)
            {
                streamReader = null;
            }
        }

        return myDataModels;
    }

}

请在主窗体中添加一个数据网格视图并将其命名为 dataGridView1。 这是主窗体的代码。

using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Threading;

namespace DataGrid
{
public partial class Form1 : Form
{

    List<MyDataModel> myDataModels = new List<MyDataModel>();

    public Form1()
    {
        InitializeComponent();
        // Read csv data at the begining
        ReadCSVData();
        // Set data in the grid
        dataGridView1.DataSource = myDataModels;

        // Then read the data file in regular interval and set in the grid
        StartAutoRefresh();
    }

    private void ReadCSVData()
    {
        CSVReader cSVReader = new CSVReader();
        var newCSVDataRows = cSVReader.GetNewCSVValue();
        if (newCSVDataRows != null)
        {
            myDataModels.AddRange(newCSVDataRows);
        }            
    }

    #region Timer 
    private static System.Timers.Timer _timer;

    private void StartAutoRefresh()
    {
        Console.WriteLine("Start the Datafetch " + DateTime.Now);

        if (_timer == null)
        {
            int dataFetchInterval = 1;

            dataFetchInterval = dataFetchInterval * 60 * 1000;

            _timer = new System.Timers.Timer(dataFetchInterval);
            _timer.Elapsed += new 
    ElapsedEventHandler(FetchTripsOfTheWeek);

            _timer.Interval = dataFetchInterval;
            _timer.Enabled = true;
        }
        else
        {
            _timer.Enabled = true;
        }

    }

    public void StopAutoRefresh()
    {
        if (_timer != null)
        {
            _timer.Enabled = false;
            _timer.Dispose();
            _timer = null;
        }
    }


    public void FetchTripsOfTheWeek(object source, ElapsedEventArgs e)
    {
        bool isResourcesLoaded = false;
        executeActionOnBackgroundThread(
           "Loading data ...",
           () =>
           {
               try
               {
                   ReadCSVData();
                   isResourcesLoaded = true;
               }
               catch (Exception exception)
               {
                   var message = exception.Message;

                   MessageBox.Show(message);

                   isResourcesLoaded = false;
               }
           },

           () =>
           {
               var result = true;
               if (isResourcesLoaded)
               {
                   // Set data in the grid
                   dataGridView1.DataSource = null;
                   dataGridView1.DataSource = myDataModels;
                   dataGridView1.Refresh();
               }
               return result;
           },

           () =>
           {
               // Do extra things, like, setting readonly mode etc
           });
    }

    private void executeActionOnBackgroundThread(string indicatorMessage, 
    System.Action backgroundAction, System.Func<bool> uiAction, 
   System.ActiononCompletedAction = null)
    {
        System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            backgroundAction?.Invoke();

            BeginInvoke(new System.Action(() =>
            {
                var success = uiAction?.Invoke();

                onCompletedAction?.Invoke();

            }), null);
        });
    }

    #endregion
}

}

您从这里下载完整的项目 https://drive.google.com/open?id=1ChLY7IydYM5OT5sOTUXjjV-6vfrgUeoD

希望您能解决问题。祝你好运。

【讨论】:

  • ReadNewCSVMethod , DisposeOfTimer , killThread 有红色代码 :(
  • "启动计时器?"在表单加载时。
  • 嗨@Fayy,答案中已添加完整的源代码。您可以从答案中提供的链接下载完整的示例项目。
  • 嗨@Fayy,如果您喜欢我的回答,请接受它作为解决方案并将其标记为有用。谢谢。
  • 嗨@Fayy 是什么错误?你能发布错误详细信息吗?
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2013-03-27
  • 2017-03-13
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多