如何将标题添加到CSV文件 [英] how to add header to CSV file

查看:629
本文介绍了如何将标题添加到CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里我创建了一个将数据从datagridview保存到csv文件的功能

但我不知道如何添加标题字段

here i create a function to save data from datagridview to csv file

but i dont know how to add header field

private void button1_Click(object sender, EventArgs e)
{
    string strValue = string.Empty;

    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        for (int j = 0; j < dataGridView1.Rows[i].Cells.Count; j++)
        {
            if (!string.IsNullOrEmpty(dataGridView1[j, i].Value.ToString()))
            {
                if (j > 0)
                    strValue = strValue + "," + dataGridView1[j, i].Value.ToString();
                else
                {
                    if (string.IsNullOrEmpty(strValue))
                        strValue = dataGridView1[j, i].Value.ToString();
                    else
                        strValue = strValue + Environment.NewLine + dataGridView1[j, i].Value.ToString();
                }
            }
        }
                
    }
           
            
    string strFile = "c:\\Active Dir File.csv";
    File.WriteAllText(strFile, strValue);
    MessageBox.Show("File Saved in C:");
}

推荐答案

在这种情况下,您可以在进入循环之前,使用等于标题行的文字字符串开始strValue. > 另外,如果您已填充标题单元格,则可以遍历这些标题单元格来构建标题行.

如果这是您的实际代码,那么我建议您也查看stringbuilder类.
In this case you could start strValue with a literal string which is equal to your header row before you go into your loop.
Alternatively if you have populated the header cells then you can loop through these to build your header row.

If this is your actual code then I would advise you to look at the stringbuilder class as well.


它们都使用相同的布局吗?

如果是,请使用该标题行创建一个文件.

然后使用DOS外壳程序并使用旧的DOS命令合并文件.

转到包含.CSV文件和头文件的文件夹,然后发出此
命令:

复制Header.txt + somefile.csv somefileNEW.csv
Do they all use the same layout?

If yes, create a file with that single header line.

Then shell to DOS and merge the files using an old DOS command.

Go to the folder that contains the .CSV files and header file and issue this
command:

copy Header.txt + somefile.csv somefileNEW.csv


这篇关于如何将标题添加到CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆