编程语言
首页 > 编程语言> > C#-Winform-DataGridView-CSV

C#-Winform-DataGridView-CSV

作者:互联网

C#-Winform-DataGridView-CSV

一、界面搭建

image

二、DataGridView基本属性

image

编辑列的选项中可以进行设计:

基本属性:

image

三、DataGridView和CSV

3.1 初始化数据

//初始化数据
private void btnInitData_Click(object sender, EventArgs e)
{
    string[] strID = new string[] {"1", "2", "3", "4", "5"};
    string[] strName = new string[] {"赵一", "钱二", "孙三", "李四", "周五"};
    string[] strAddress = new string[] {"黑龙江", "江苏", "西藏", "新疆", "内蒙古"};
    string[] strPhone = new string[] { "86-451", "86-025	", "0891", "0995", "0477" };

    gridTestData.Rows.Add(5);
    for (int i = 0; i < gridTestData.Rows.Count; i++)
    {
        gridTestData.Rows[i].Cells[0].Value = strID[i];
        gridTestData.Rows[i].Cells[1].Value = strName[i];
        gridTestData.Rows[i].Cells[2].Value = strAddress[i];
        gridTestData.Rows[i].Cells[3].Value = strPhone[i];

    }
}

image

3.2 导出为CSV文件

//保存数据到csv文件
private void btnSaveToCSV_Click(object sender, EventArgs e)
{
    //实例化SaveFileDialog
    SaveFileDialog saveFileDialog = new SaveFileDialog();
    saveFileDialog.Filter = "Execl files (*.csv)|*.csv";
    saveFileDialog.FilterIndex = 0;
    saveFileDialog.RestoreDirectory = true;
    saveFileDialog.CreatePrompt = true;
    saveFileDialog.Title = "保存为csv文件";

    //打开SaveFileDialog控件
    if (saveFileDialog.ShowDialog() == DialogResult.OK)
    {
        //数据流变量
        Stream myStream;
        //返回SaveFileDialog控件,并将所选择的文件转化成流
        myStream = saveFileDialog.OpenFile();
        //将选择的文件流生成写入流
        StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
        string columnTitle = "";
        try
        {
            //写入列标题
            for (int i = 0; i < gridTestData.ColumnCount; i++)
            {
                if (i > 0)
                {
                    columnTitle += ",";
                }
                columnTitle += gridTestData.Columns[i].HeaderText;
            }
            //将内容写入文件流中
            sw.WriteLine(columnTitle);

            for (int j = 0; j < gridTestData.Rows.Count; j++)
            {
                string columnValue = "";
                for (int k = 0; k < gridTestData.Columns.Count; k++)
                {
                    if (k > 0)
                    {
                        columnValue += ",";
                    }
                    if (gridTestData.Rows[j].Cells[k].Value == null)
                    {
                        columnValue += "";
                    }
                    else if (gridTestData.Rows[j].Cells[k].Value.ToString().Contains(","))
                    {
                        //将单元个中的,转义成文本
                        columnValue += "\"" + gridTestData.Rows[j].Cells[k].Value.ToString().Trim() + "\"";
                    }
                    else
                    {
                        //横向跳格
                        columnValue += gridTestData.Rows[j].Cells[k].Value.ToString().Trim() + "\t";
                    }
                }
                //内容写入文件流中
                sw.WriteLine(columnValue);
            }
            sw.Close();
            myStream.Close();
            MessageBox.Show("导出表格成功!");
        }
        catch (Exception)
        {
            MessageBox.Show("导出表格失败!");
        }
        finally
        {
            sw.Close();
            myStream.Close();
        }
    }
    else
    {
        MessageBox.Show("取消导出表格操作!");
    }
}

image

3.3 导入CSV文件

public class CSVExample
{
    public string id;
    public string name;
    public string address;
    public string phone;

    public static CSVExample FromCsv(string csvContent)
    {
        string[] values = csvContent.Split(',');
        CSVExample example = new CSVExample();
        example.id = values[0];
        example.name = values[1];
        example.address = values[2];
        example.phone = values[3];

        return example;
    }
}
//将csv文件转成list,并绑定到DataGridView组件上
private void btnCSVToGrid_Click(object sender, EventArgs e)
{
    //实例化SaveFileDialog
    OpenFileDialog openFileDialog = new OpenFileDialog();
    openFileDialog.Filter = "Execl files (*.csv)|*.csv";
    openFileDialog.FilterIndex = 0;
    openFileDialog.RestoreDirectory = true;
    openFileDialog.Title = "打开的文件";

    //打开SaveFileDialog控件
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        string path = Path.GetFullPath(openFileDialog.FileName);
        //MessageBox.Show(path);
        List<CSVExample> values = File.ReadAllLines(path, System.Text.Encoding.GetEncoding(-0))
            .Skip(1)
            .Select(v => CSVExample.FromCsv(v))
            .ToList();
        //MessageBox.Show(values.Count.ToString());
        gridTestWrite.Rows.Add(values.Count);
        for (int i = 0; i < values.Count; i++)
        {
            gridTestWrite.Rows[i].Cells[0].Value = values[i].id + ".csv";
            gridTestWrite.Rows[i].Cells[1].Value = values[i].name + ".csv";
            gridTestWrite.Rows[i].Cells[2].Value = values[i].address + ".csv";
            gridTestWrite.Rows[i].Cells[3].Value = values[i].phone + ".csv";



        }
    }
}

image

标签:Rows,string,datagridview,C#,Value,DataGridView,gridTestData,values,CSV
来源: https://www.cnblogs.com/jsit-dj-it/p/16559565.html