首页 > 编程语言 >C#应用下的CSV文件写入和读出

C#应用下的CSV文件写入和读出

时间:2024-05-07 16:24:29浏览次数:52  
标签:string C# 读出 filestream new dt CSV my DataTable

1. 建立DataTable 类型

DataTable my_accurdt;
my_accurdt = new DataTable(DateTime.Now.ToString("yMMddHHmm") + "_AccurData");

2. 创建DataTable的列和行

//列
my_accurdt.Columns.Add(new DataColumn("Oder", typeof(int)));
my_accurdt.Columns.Add(new DataColumn("TimeStamp", typeof(string)));

//行
DataRow my_rows = my_accurdt.NewRow();
my_rows["Oder"] = dataTableOrder;
my_rows["TimeStamp"] = DateTime.Now.ToString("yMMddHHmm");
my_accurdt.Rows.Add(my_rows);

3. 把DataTable显示在WinForm的dataGridView控件中

Accur_table_dataGridView.DataSource = my_accurdt;

4. 创建写入CSV文件方法

        //write function
        public void writeDataCSV(string file_path, DataTable my_dt)
        {
            FileStream my_filestream;
            StreamWriter my_streamwriter;
            string my_data = null;
            if (!File.Exists(file_path))
            {
                my_filestream = new FileStream(file_path, FileMode.Create, FileAccess.Write);
                my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8);
                //write columns name
                for (int i = 0; i < my_dt.Columns.Count; i++)
                {
                    my_data += my_dt.Columns[i].ColumnName.ToString();
                    if (i < my_dt.Columns.Count - 1)
                    {
                        my_data += ",";
                    }
                }
                my_streamwriter.WriteLine(my_data);
            }
            else
            {
                my_filestream = new FileStream(file_path, FileMode.Append, FileAccess.Write);
                my_streamwriter = new StreamWriter(my_filestream, Encoding.UTF8);
            }
            //write rows
            for (int i = 0; i < my_dt.Rows.Count; i++)
            {
                my_data = null;
                for (int j = 0; j < my_dt.Columns.Count; j++)
                {
                    my_data += my_dt.Rows[i][j].ToString();
                    if (j < my_dt.Columns.Count - 1)
                    {
                        my_data += ",";
                    }
                }
                my_streamwriter.WriteLine(my_data);
            }
            my_streamwriter.Close();
            my_filestream.Close();
        }

5. 创建读出CSV文件方法

        //read function
        public DataTable readDataCSV(string file_path)
        {
            DataTable my_dt = new DataTable();
            FileStream my_filestream = new FileStream(file_path, FileMode.Open, FileAccess.Read);
            StreamReader my_streamreader = new StreamReader(my_filestream, Encoding.UTF8);
            string my_strLine = null;
            string[] my_arrayLine = null;
            bool isFirst = true;
            int my_dtColumns = 0;

            while ((my_strLine = my_streamreader.ReadLine()) != null)
            {
                my_strLine = my_strLine.Trim();
                my_arrayLine = my_strLine.Split(',');

                if (isFirst)
                {
                    my_dtColumns = my_arrayLine.Length;
                    for (int i = 0; i < my_dtColumns; i++)
                    {
                        my_dt.Columns.Add(my_arrayLine[i]);
                    }
                    isFirst = false;
                }
                else
                {
                    DataRow my_datarow = my_dt.NewRow();
                    for (int j = 0; j < my_dtColumns; j++)
                    {
                        if (my_arrayLine.Length > j)
                        {
                            my_datarow[j] = my_arrayLine[j];
                        }
                    }
                    my_dt.Rows.Add(my_datarow);
                }
            }
            my_streamreader.Close();
            my_filestream.Close();
            return my_dt;
        }

6. 创建文件保存路径选择框

        //file storage path
        public string SelectFolderPath()
        {
            string my_folderpath = string.Empty;
            FolderBrowserDialog my_folderbrowser = new FolderBrowserDialog();
            DialogResult my_result = my_folderbrowser.ShowDialog();
            if (my_result == DialogResult.OK)
            {
                my_folderpath = my_folderbrowser.SelectedPath;
                return my_folderpath;
            }
            else
            { return string.Empty; }
        }

标签:string,C#,读出,filestream,new,dt,CSV,my,DataTable
From: https://www.cnblogs.com/xiacuncun/p/18177610

相关文章

  • docker - [13] docker网络
    smosmosmo"狂神"omzomzomz 一、理解网络本机回环地址:127.0.0.1本机IP地址:192.168.2.131docker地址:172.17.0.1  1.1、docker如何处理容器网络访问的?首先,拉取一个tomcat镜像(我直接从之前制作的tomcat镜像拉取下来了)拉取之后修改了一下名字:dockertag<imageI......
  • .net 8中使用过滤器记录系统日志 ActionFilter+Serilog
    1、添加自定义日志过滤器类usingSerilog;usingMicrosoft.AspNetCore.Mvc.Filters;namespaceADTO.CMS.Common.Filter{///<summary>///日志记录过滤器///</summary>publicclassLogActionFilter:IActionFilter{///<summary>///......
  • [网鼎杯 2020 白虎组]PicDown linux文件工作原理
    今天遇到个毫无头绪的题,记录一下过程。进入页面发现输入框,参数为url,那就试试文件读取。看看环境变量。其中PWD=/app,有可能存在app.py,试试吧。猜对了,运气吧~(做完后才发现的T-T)这里看其他wp说是在linux读取当前进程执行命令/proc/self/cmdline发现了看看app.py吧。点......
  • C#获取计算机唯一标识组装GUID ,延伸ManagementClass、WIN32_类库名
    usingSystem.Management;usingSystem.Security.Cryptography;usingSystem.Text;namespaceSWin{publicclassComGUID{privatestaticstringcomputerGUID=string.Empty;publicstaticstringValue(){if(str......
  • TheadLocal类学习
    ThreadLocal是Java中一个非常实用的线程相关的类,它提供线程本地变量,即每个线程都有自己独立的变量副本,从而避免了线程安全问题。下面我将通过几个方面来帮助你理解并学习如何使用ThreadLocal。基本概念线程局部变量:每个线程都拥有一份 ThreadLocal 变量的副本,彼此之间互......
  • Unity性能优化——合批(Batching)的限制与失败原因汇总
    Unity中Batching大致可以分为StaticBatching,DynamicBatching,SRPBatching与GPUInstancing四大类,但在使用时我们经常会遇到合批失败的情况,这里汇总了四大类的合批使用限制与合批失败的关键错误信息.StaticBatching的限制额外的内存开销64000个顶点限制影响......
  • [转]openEuler 22.03 (LTS-SP1)安装最新版Docker(踩坑及解决方案)
    原文地址:openEuler22.03(LTS-SP1)安装最新版Docker(踩坑及解决方案)_openeulerdocker-CSDN博客openEuler22.03LTS-SP1要是直接yuminstalldocker,默认安装docker是18.09.0,这个版本Docker有个bug,所以还是安装个最新版Docker。1、先增加docker官方仓库[[email protected]......
  • oracle表导出mysql适用的脚本方法
    oracle表导出mysql适用的脚本方法1.在对应的oracle数据库plsql中执行下面代码,建F_LIMS_GET_SQL_FOR_MYSQL函数CREATEORREPLACEFUNCTIONF_LIMS_GET_SQL_FOR_MYSQL(PI_TABLENAMEINVARCHAR2,PI_ISDROPININTEGER:=1......
  • DNS/DHCP 服务器
    DNS/DHCP服务器(Dnsmasq)(01)安装DnsmasqDnsmasq:安装  安装Dnsmasq,它是轻量级的DNS转发器和DHCP服务器软件。[1] 安装Dnsmasq。root@dlp:~#apt-yinstalldnsmasq [2] 配置Dnsmasq。root@dlp:~#vi/etc/dnsmasq.conf#line19:uncomment#neverforwar......
  • [Unit testing - React] Use the waitForElementToBeRemoved Async Util to Await Unt
    Sometimes,youmightneedtowaitforanelementtodisappearfromyourUIbeforeproceedingwithyourtestsetupormakingyourassertion.Inthislesson,wewilllearnaboutawrapperaroundthewaitForthatallowsyoutowaituntilanelementisremove......