欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# winform操作CSV格式文件

 更新時(shí)間:2025年03月06日 16:05:07   作者:_Csharp  
這篇文章主要為大家詳細(xì)介紹了C#在winform中的表格操作CSV格式文件的相關(guān)實(shí)例,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以參考一下

實(shí)例一

實(shí)例效果

當(dāng)在winform界面中點(diǎn)擊讀取按鈕時(shí) 將csv中的所有數(shù)據(jù)讀取出來(lái)放置在datagridview控件,可以在datagridview控件中編輯數(shù)據(jù),當(dāng)點(diǎn)擊保存按鈕時(shí) 將datagridview控件中的所有數(shù)據(jù)存儲(chǔ)在csv格式文件中。

實(shí)現(xiàn)代碼

第一步UI界面搭建

第二步封裝一個(gè)csv文件格式的操作類(lèi)

public class CSVAPI
{
    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="date"></param>
    /// <param name="data"></param>
    /// <param name="result"></param>
    /// <param name="fileName"></param>
    public void SaveData(string date,string data, string result,string fileName)
    {
        using (StreamWriter sw2 = new StreamWriter(fileName, true, Encoding.Default))
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(date).Append(",").Append(data).Append(",").Append(result + "\n");
            sw2.Write(sb.ToString());
        }
    }
 
    /// <summary>
    /// 讀取CSV
    /// </summary>
    /// <returns></returns>
    public string ReadData(string fileName)
    {
        StreamReader sr = new StreamReader(fileName, Encoding.Default);
        string s = sr.ReadToEnd(); // 讀取數(shù)據(jù)
        sr.Close();
        sr.Dispose();
        return s;
    }
}

第三步實(shí)現(xiàn)按鈕事件

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    CSVAPI csv = new CSVAPI();
    string filename = "./data.csv";
    /// <summary>
    /// 保存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
        if (dataGridView1.Rows.Count>0)
        {
            //  寫(xiě)入表頭(將表頭寫(xiě)死)
            FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
            StreamWriter sw = new StreamWriter(fs, Encoding.Default);
            StringBuilder sb = new StringBuilder(); // 定義可變字符串,保存存儲(chǔ)的數(shù)據(jù)
            sb.Append("時(shí)間").Append(",").Append("姓名").Append(",").Append("事件");
            sw.WriteLine(sb);
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();
            
            for (int i = 0; i < this.dataGridView1.RowCount-1; i++)
            {
                csv.SaveData(this.dataGridView1.Rows[i].Cells[0].Value.ToString()+"", this.dataGridView1.Rows[i].Cells[1].Value.ToString() + "", this.dataGridView1.Rows[i].Cells[2].Value.ToString() + "", filename);
            }
        }
    }
 
    /// <summary>
    /// 讀取
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
        this.dataGridView1.Rows.Clear();
        if (!File.Exists(filename))
        {
            MessageBox.Show("文件不存在");
            return;
        }
        string[] strings = csv.ReadData(filename).Split('\n');
        
        for (int i = 1;i < strings.Length;i++)
        {
            if (!string.IsNullOrEmpty(strings[i]))
            {
                string[] vals = strings[i].Split(',');
                this.dataGridView1.Rows.Add(vals);
            }
        }
    }
}

效果展示

實(shí)例二

實(shí)例效果

當(dāng)在winform界面中點(diǎn)擊讀取按鈕時(shí)彈出文件選擇框,用戶(hù)選擇指定的csv文件然后將csv中的所有數(shù)據(jù)讀取出來(lái)放置在datagridview控件,可以在datagridview控件中編輯數(shù)據(jù),當(dāng)點(diǎn)擊保存按鈕時(shí) 將datagridview控件中的所有數(shù)據(jù)存儲(chǔ)在用戶(hù)選擇的csv格式文件路徑中。

完整代碼

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
 
    OpenFileDialog ofd = new OpenFileDialog();
    //讀取
    private void button1_Click(object sender, EventArgs e)
    {
        //字符串-->dataTable--->dataSource
        if(ofd.ShowDialog()==DialogResult.OK)
        {
            FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
            StreamReader sr = new StreamReader(fs,Encoding.Default);//讀取文件流數(shù)據(jù)
            string data = "";//讀出每一行的數(shù)據(jù) "name ,age sex"
            string[] lines;// 數(shù)據(jù)的數(shù)組
            bool isHead = true; // 是否是表頭
            DataTable dt = new DataTable();// 為了給datagridview設(shè)置數(shù)據(jù)源的類(lèi)型
            while ((data=sr.ReadLine())!=null)  //先賦值給data 再判斷data是否為空 ,不為空時(shí)候 一直讀取
            {
 
                lines= data.Split(','); //把每一行的數(shù)據(jù)使用逗號(hào)分隔 [name ,age ,sex]
                if(isHead) //是不是表頭[name ,age ,sex] 
                {
                    //遍歷表頭數(shù)組 給每一列添加標(biāo)題
                    for(int i = 0; i < lines.Length; i++)
                    {
                        dt.Columns.Add(lines[i]); //設(shè)置dt的列的數(shù)據(jù)源
                    }
 
                    isHead = false;
                }
                else //不是表頭數(shù)據(jù),每一行表格添加數(shù)據(jù)
                {
                    DataRow d1 = dt.NewRow();// 指定datatable創(chuàng)建行
                    for (int i = 0; i < lines.Length; i++)
                    {
                        d1[i] = lines[i];// 單元格設(shè)置值
                    }
                    dt.Rows.Add(d1);
 
                }
 
            }
            //綁定數(shù)據(jù)源
            if (dt.Rows.Count==0) //如果沒(méi)行的 證明沒(méi)數(shù)據(jù)
            {
                MessageBox.Show("沒(méi)有數(shù)據(jù)","溫馨提示");
            }
            else
            {
                //證明有數(shù)據(jù) 展示到控件上
                //dataGridView1.DataSource = dt;
                // dataGridView1.ColumnCount 列的個(gè)數(shù)
                dataGridView1.ColumnCount = dt.Columns.Count;
                //設(shè)置表頭
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    // dataGridView1.Columns[i].HeaderText  表格控件的每一列的標(biāo)題
                    dataGridView1.Columns[i].HeaderText = dt.Columns[i].ColumnName;
                }
 
                //設(shè)置行數(shù)據(jù)
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //dataGridView1.Rows. 設(shè)置表格控件的所有的行
                    dataGridView1.Rows.Add(dt.Rows[i].ItemArray);
                }
            }
 
            sr.Close();
            fs.Close();
        }
    }
 
    // 保存
    private void button2_Click(object sender, EventArgs e)
    {
        //dataSource-->dataTable--->string
        DataTable dt  = new DataTable(); //創(chuàng)建dataTable類(lèi)型
 
        //設(shè)置dt表頭
        //遍歷控件列的個(gè)數(shù),根據(jù)控件的列的個(gè)數(shù)設(shè)置dt列
        for (int i = 0;i < dataGridView1.Columns.Count;i++)
        {
            dt.Columns.Add(dataGridView1.Columns[i].HeaderText); //把控件列標(biāo)題添加到dt列里面
        }
 
        //設(shè)置dt的行 
        for (int i = 0; i < dataGridView1.Rows.Count; i++) //遍歷控件幾行
        {
            DataRow row = dt.NewRow(); //創(chuàng)建行
            for (int j = 0; j < dataGridView1.Columns.Count; j++) //遍歷控件幾列
            {
                //dataGridView1[0,0] 根據(jù)幾行幾列取出表格數(shù)據(jù)
                row[j] = dataGridView1[j, i].Value;
            }
            dt.Rows.Add(row);
        }
      
        //把dt數(shù)據(jù)轉(zhuǎn)成字符串進(jìn)行寫(xiě)入
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "csv文件(*.csv)|.csv";
        if(sfd.ShowDialog()==DialogResult.OK)
        {
            //開(kāi)始寫(xiě)入
            FileStream fs = new FileStream(sfd.FileName, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs,Encoding.Default);
            string data = "";// 寫(xiě)入的字符串
 
            //表頭轉(zhuǎn)成字符串
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                data += dt.Columns[i].ColumnName;// 把dt列標(biāo)題取出拼接
                if(i <dt.Columns.Count-1)
                {
                    data += ","; // 列之間使用逗號(hào)隔開(kāi)
                }
 
            }
            sw.WriteLine(data); //寫(xiě)入表頭
 
            //寫(xiě)入行數(shù)據(jù)
            data = null;//防止表頭數(shù)據(jù)重復(fù)寫(xiě)入
            for (int i = 0; i < dt.Rows.Count-1; i++)
            {
                for (int j = 0; j <dt.Columns.Count; j++)
                {
                    data += dt.Rows[i][j]; //幾行幾列數(shù)據(jù)拼接data
                    if(j<dt.Columns.Count-1)//不是最后一列
                    {
                        data += ",";
                    }
                }
                sw.WriteLine(data);//寫(xiě)入表數(shù)據(jù)
                data=null;
            }
 
            sw.Close();
            fs.Close();
 
        }
            
    }
}

1 datagridview 控件的常用屬性

  • dataGridView1.Columns  表格控件的所有列
  • dataGridView1.Columns .Count 表格控件的所有列的個(gè)數(shù)
  • dataGridView1.Rows  表格控件的所有行
  • dataGridView1[0,0] 根據(jù)幾行幾列取出表格數(shù)據(jù)
  • dataGridView1.Columns[i].HeaderTex  表格控件的列的文本內(nèi)容

2 dataTable常用的屬性和方法

  • DataTable dt  = new DataTable(); 創(chuàng)建dataTable類(lèi)型
  • DataRow row = dt.NewRow(); 創(chuàng)建一行
  • dt.Rows.Add(row);  向dataTable添加一行
  • dt.Columns.Add(); 向dataTable添加一列
  • dt.Columns  datatable所有的列
  • dt.Rows   datatable所有的行
  • dt.Columns[i].ColumnName;列標(biāo)題

以上就是C# winform操作CSV格式文件的詳細(xì)內(nèi)容,更多關(guān)于C#操作CSV的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • C# 多線(xiàn)程編程技術(shù)基礎(chǔ)知識(shí)入門(mén)

    C# 多線(xiàn)程編程技術(shù)基礎(chǔ)知識(shí)入門(mén)

    這篇文章主要介紹了C# 多線(xiàn)程編程技術(shù)基礎(chǔ)知識(shí),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2020-02-02
  • C#使用log4net記錄日志的方法步驟

    C#使用log4net記錄日志的方法步驟

    本文主要介紹了C#使用log4net記錄日志的方法步驟,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • C#中的尾遞歸與Continuation詳解

    C#中的尾遞歸與Continuation詳解

    這篇文章主要介紹了C#中的尾遞歸與Continuation詳解,本文講解了遞歸與尾遞歸、尾遞歸與Continuation、Continuation的改進(jìn)等內(nèi)容,需要的朋友可以參考下
    2015-06-06
  • C# StreamReader類(lèi)實(shí)現(xiàn)讀取文件的方法

    C# StreamReader類(lèi)實(shí)現(xiàn)讀取文件的方法

    這篇文章主要介紹了C# StreamReader類(lèi)實(shí)現(xiàn)讀取文件的方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-01-01
  • C#中FileSystemWatcher的使用教程

    C#中FileSystemWatcher的使用教程

    這篇文章主要給大家介紹了關(guān)于C#中FileSystemWatcher使用的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-12-12
  • C#實(shí)現(xiàn)帶行數(shù)和標(biāo)尺的RichTextBox

    C#實(shí)現(xiàn)帶行數(shù)和標(biāo)尺的RichTextBox

    這篇文章主要為大家詳細(xì)介紹了如何利用C#實(shí)現(xiàn)帶行數(shù)和標(biāo)尺的RichTextBox,文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)C#有一定的幫助,感興趣的小伙伴可以跟隨小編一起了解一下
    2022-12-12
  • Unity使用LineRender實(shí)現(xiàn)繪畫(huà)功能

    Unity使用LineRender實(shí)現(xiàn)繪畫(huà)功能

    這篇文章主要為大家詳細(xì)介紹了Unity使用LineRender實(shí)現(xiàn)繪畫(huà)功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-07-07
  • C#四舍五入用法實(shí)例

    C#四舍五入用法實(shí)例

    這篇文章主要為大家詳細(xì)介紹了C#四舍五入用法實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-02-02
  • C#提取PDF中指定文本與圖片坐標(biāo)的示例代碼

    C#提取PDF中指定文本與圖片坐標(biāo)的示例代碼

    這篇文章主要為大家詳細(xì)介紹了如何使用國(guó)產(chǎn)PDF庫(kù)通過(guò)C# 提取PDF中指定文本或圖片的坐標(biāo)位置(X, Y軸),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-12-12
  • C#實(shí)現(xiàn)飛行棋游戲

    C#實(shí)現(xiàn)飛行棋游戲

    這篇文章主要為大家詳細(xì)介紹了C#實(shí)現(xiàn)飛行棋游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07

最新評(píng)論