首先本人的需求是,通过UI编辑一个表格文件,然后将其存储起来。
同时也可以对其进行载入,话不多说先上图片
dataGridView1 的初始化,这个控件的初始化可以使用UI界面的设置,也可以使用程序:
Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn();Column3 = new System.Windows.Forms.DataGridViewTextBoxColumn();Column4 = new System.Windows.Forms.DataGridViewTextBoxColumn();this.Column1.Name = "Column1";this.Column2.Name = "Column2";this.Column3.Name = "Column3";this.Column4.Name = "Column4";Column1.HeaderText = "抓手No";Column2.HeaderText = "X";Column3.HeaderText = "Y";Column4.HeaderText = "Z";dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {Column1,Column2,Column3,Column4});
增加一行的代码如下:
int idx= dataGridView1.Rows.Add(1);dataGridView1.Rows[idx].Cells[0].Value = idx.ToString();dataGridView1.Rows[idx].Cells[1].Value = tBx.Text.ToString();dataGridView1.Rows[idx].Cells[2].Value = tBy.Text.ToString();dataGridView1.Rows[idx].Cells[3].Value = tBz.Text.ToString();
删除行尾:
int idx = dataGridView1.RowCount - 1;dataGridView1.Rows.RemoveAt(idx);
删除选中行:
for (int i = dataGridView1.SelectedRows.Count; i > 0; i--){dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[i - 1].Index);}
读写文件整理到了这个工具类里:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;namespace buttonMV
{class CsvHelper{public DataTable readCSV(){//获取文件名string strFileName = "";OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = "CSV文件(*.csv)|*.csv|word文档(*.doc;*.docx)|*.doc;*.docx|所有文件|*.*";ofd.ValidateNames = true; // 验证用户输入是否是一个有效的Windows文件名ofd.CheckFileExists = true; //验证路径的有效性ofd.CheckPathExists = true;//验证路径的有效性if (ofd.ShowDialog() == DialogResult.OK) //用户点击确认按钮,发送确认消息{strFileName = ofd.FileName;//获取在文件对话框中选定的路径或者字符串}string filePath = strFileName;var dt = new DataTable();// Creating the columnsFile.ReadLines(filePath).Take(1).SelectMany(x => x.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)).ToList().ForEach(x => dt.Columns.Add(x.Trim()));// Adding the rowsFile.ReadLines(filePath).Skip(1).Select(x => x.Split(',')).ToList().ForEach(line => dt.Rows.Add(line));return dt;}public void DataGridViewToExcel(DataGridView dgv){//程序实例化SaveFileDialog控件,并对该控件相关参数进行设置SaveFileDialog dlg = new SaveFileDialog();dlg.Filter = "Execl files (*.csv)|*.csv";dlg.FilterIndex = 0;dlg.RestoreDirectory = true;dlg.CreatePrompt = true;dlg.Title = "保存为csv文件";//以上过程也可以通过添加控件,再设置控件属性完成,此处用程序编写出来了,在移植时就可摆脱控件的限制if (dlg.ShowDialog() == DialogResult.OK)//打开SaveFileDialog控件,判断返回值结果{Stream myStream;//流变量myStream = dlg.OpenFile();//返回SaveFileDialog控件打开的文件,并将所选择的文件转化成流StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));//将选择的文件流生成写入流string columnTitle = "";try{//写入列标题 for (int i = 0; i < dgv.ColumnCount; i++){if (i > 0){columnTitle += ",";}columnTitle += dgv.Columns[i].HeaderText;//符号 , 的添加,在保存为Excel时就以 , 分成不同的列了}sw.WriteLine(columnTitle);//将内容写入文件流中//写入列内容 for (int j = 0; j < dgv.Rows.Count; j++){string columnValue = "";for (int k = 0; k < dgv.Columns.Count; k++){if (k > 0){columnValue += ",";}if (dgv.Rows[j].Cells[k].Value == null)columnValue += "";else if (dgv.Rows[j].Cells[k].Value.ToString().Contains(",")){columnValue += "\"" + dgv.Rows[j].Cells[k].Value.ToString().Trim() + "\"";//将单元格中的,号转义成文本}else{columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim() + "\t";//\t 横向跳格}}//获得写入到列中的值sw.WriteLine(columnValue);//将内容写入文件流中}sw.Close();//关闭写入流myStream.Close();//关闭流变量MessageBox.Show("导出表格成功!");}catch (Exception e){MessageBox.Show("导出表格失败!");}finally{sw.Close();myStream.Close();}}else{MessageBox.Show("取消导出表格操作!");}}}
}
导出文件:
CsvHelper csvWriter = new CsvHelper();csvWriter.DataGridViewToExcel(dataGridView1);
导入文件:
CsvHelper csvReader = new CsvHelper();DataTable table = csvReader.readCSV();//获取表格的列数int columNum = table.Columns.Count;foreach (DataRow row in table.Rows){int idx = dataGridView1.Rows.Add(1);for (int i = 0; i < columNum; i++){string columName = table.Columns[i].ColumnName;dataGridView1.Rows[idx].Cells[i].Value = row[columName].ToString();}}
扩展:C#中DataGridView控件使用大全及C#学习心得-CSDN博客