C#读写并修改csv文件特定列或行的值,例如cos和sin值

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;

namespace CSVHelper
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            form1 = this; //相当于该窗体类的实例赋给了该静态变量form
        }
        public static Form1 form1;

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
           if (openFile.ShowDialog() == DialogResult.OK)
            {
                string path = openFile.FileName;
                DataTable dt = CSVHelper.ReadCSV(path);

                CSVHelper.WriteCSV("C:/Users/dell/Desktop/实验5.csv",dt);//设置自己想要的保存位置
            }
        }

    }
}

这是FORM的代码。

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

namespace CSVHelper
{
    public class CSVHelper
    {
        /// <summary>
        /// 写入CSV
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="dt">要写入的datatable</param>
        public static void WriteCSV(string fileName, DataTable dt)
        {
            FileStream fs;
            StreamWriter sw;
            string data = null;
            //判断文件是否存在,存在就不再次写入列名
            if (File.Exists(fileName))
            {
                fs = new FileStream(fileName, FileMode.Create, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);

                //写出列名称
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    data += dt.Columns[i].ColumnName.ToString();
                    if (i < dt.Columns.Count - 1)
                    {
                        data += ",";//中间用,隔开
                    }
                }
                sw.WriteLine(data);
            }
            else
            {
                fs = new FileStream(fileName, FileMode.Append, FileAccess.Write);
                sw = new StreamWriter(fs, Encoding.UTF8);
            }
            //int jiange = (Convert.ToInt32(form1.textBox3.Text));
            for (int i = 0; i < dt.Rows.Count; i++) //写出各行数据
            {
                data = null;
                int jiange = 10; //Convert.ToInt32((Form1.form1.textBox3.Text));//设置循环间隔
                int sinlie = 6;// Convert.ToInt32((Form1.form1.textBox5.Text));//设置sin值的初始循环位
                int mi = 180;// Convert.ToInt32 (Form1.form1.textBox1.Text);//设置循环的初始值
                int coslie = 5;// Convert.ToInt32(Form1.form1.textBox4.Text);//设置cos值的初始循环位
                for (int j = 0; j < dt.Columns.Count; j++)//历遍每一列填充数据
                {                  
                    if ((j < dt.Columns.Count - 1))//数据处理
                    {
                        if (j == Convert.ToInt32(coslie) + (Convert.ToInt32(jiange)))//cos值处理
                            {
                                try
                                {
                                    double X = (Math.PI * Convert.ToDouble(dt.Rows[i][6])) / 180;//求弧度值
                                data += 30;// ((Convert.ToInt32(mi) * (Math.Cos(X))).ToString());//写入数据
                                }
                                catch (Exception)
                                {
                                    data += ("0");
                                }
                            }
                        if (j == Convert.ToInt32(sinlie) + Convert.ToInt32(jiange))//sin值处理
                        {
                            try
                            {
                                double X = (Math.PI * Convert.ToDouble(dt.Rows[i][6])) / 180;//求弧度值
                                data += ((Convert.ToInt32(mi) * (Math.Sin(X))).ToString());//写入数据
                                jiange += 10;// (Convert.ToInt32(Form1.form1.textBox3.Text));//增加间隔值
                                mi += 30;// (Convert.ToInt32(Form1.form1.textBox2.Text));//初始数据增加
                            }
                            catch (Exception)
                            {
                                data += ("0");
                            }
                        }
                        if ((j != Convert.ToInt32(sinlie) + Convert.ToInt32(jiange))&& (j != Convert.ToInt32(coslie) + (Convert.ToInt32(jiange))))
                        {
                            data += dt.Rows[i][j].ToString();//普通数据处理
                        }
                    }
                    
                    if (j < dt.Columns.Count - 1)
                    {
                        data += ",";//中间用,隔开
                    }
                }
                sw.WriteLine(data);//写入一行数据
            }
            sw.Close();
            fs.Close();
            MessageBox.Show("数据修改完成!", "新消息", MessageBoxButtons.OKCancel);//数据修改完成提示
        }



        /// <summary>
        /// 读取CSV文件
        /// </summary>
        /// <param name="fileName">文件路径</param>
        public static DataTable ReadCSV(string fileName)
        {
            DataTable dt = new DataTable();
            FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);

            //记录每次读取的一行记录
            string strLine = null;
            //记录每行记录中的各字段内容
            string[] arrayLine = null;
            //判断,若是第一次,建立表头
            bool isFirst = true;

            //列的个数
            int dtColumns = 0;

            //逐行读取CSV文件
            while ((strLine = sr.ReadLine()) != null)
            {
                strLine = strLine.Trim();//去除头尾空格
                arrayLine = strLine.Split(',');//分隔字符串,返回数组

                if (isFirst) //建立表头
                {
                    dtColumns = arrayLine.Length;//列的个数
                    for (int i = 0; i < dtColumns; i++)
                    {
                        dt.Columns.Add(arrayLine[i]);//每一列名称
                    }
                    isFirst = false;
                }
                else   //表内容,另建一行
                {
                    DataRow dataRow = dt.NewRow();//新建一行
                    for (int j = 0; j < dtColumns; j++)
                    {
                        if (arrayLine.Length > j)
                        {
                            dataRow[j] = arrayLine[j];
                        }
                    }
                    dt.Rows.Add(dataRow);//添加一行
                }
            }
            sr.Close();
            fs.Close();

            return dt;
        }
    }
}

这是读写修改CSV文件的代码。

  • 9
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值