使用 C# 将数据附加到 .csv 文件

发布于 2024-09-18 18:15:11 字数 675 浏览 6 评论 0原文

以下代码写入数据并且工作正常,但我想在 .csv 文件中添加多个客户端(可能是 10 个)。我怎样才能做到这一点。提前致谢。

private void createFileButton_Click(object sender, EventArgs e)
{
    string newFileName = "C:\\client_20100913.csv";

    string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;

    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
    File.AppendAllText(newFileName, clientDetails);

    MessageBox.Show("Client Added", "Added", MessageBoxButtons.OK); 
}

The following code writes the data and is working fine, but I want to add more than one client (maybe 10) in the .csv file. How can I achieve this. Thanks in advance.

private void createFileButton_Click(object sender, EventArgs e)
{
    string newFileName = "C:\\client_20100913.csv";

    string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;

    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
    File.AppendAllText(newFileName, clientDetails);

    MessageBox.Show("Client Added", "Added", MessageBoxButtons.OK); 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

落花浅忆 2024-09-25 18:15:11

如果您想将客户端信息附加到现有文件中,可以这样做:

string newFileName = "C:\\client_20100913.csv";

string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;


if (!File.Exists(newFileName))
{
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

File.AppendAllText(newFileName, clientDetails);

这样,仅在创建文件时第一次写入标题行。

尽管提供一个列表详细信息视图可能会更好,该视图可让您查看所有客户端、添加和删除客户端、选择客户端来编辑详细信息以及保存包含所有客户端的完整文件。

If you want to append the client information to an existing file, how about:

string newFileName = "C:\\client_20100913.csv";

string clientDetails = clientNameTextBox.Text + "," + mIDTextBox.Text + "," + billToTextBox.Text;


if (!File.Exists(newFileName))
{
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

File.AppendAllText(newFileName, clientDetails);

This way the header line is only written the first time, when the file is created.

Although it would probably be even nicer to provide a list-detail view that lets you view all clients, add and remove clients, select a client to edit details, and save the complete file with all clients.

享受孤独 2024-09-25 18:15:11

在我看来,您希望每次单击按钮时都会添加一个新客户端。

如果是这种情况,它当前不起作用的原因是该文件正在被行清除。

File.WriteAllText(newFileName, clientHeader);

最简单的更改是在写入之前检查文件是否存在:

if (!File.Exists(newFileName))
{
    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

尽管您可以使用其他策略,例如创建应用程序启动时的文件并保持打开状态(使用诸如 StreamWriter 之类的东西)。然后,当您的应用程序退出时,您将关闭编写器。这几乎可以保证在您的应用程序打开时文件不会被弄乱。

您可能想要这样做,因为该代码中存在竞争条件 - 在检查文件是否存在之后,在写入文件之前,用户可以删除它。保持文件打开有助于避免这种情况,但您可能愿意也可能不想这样做。

It looks to me like you want a new client to be added every time you click the button.

If that's the case, the reason why it doesn't work currently is that the file is being cleared by the line

File.WriteAllText(newFileName, clientHeader);

The simplest change would be to check if the file exists before writing over it:

if (!File.Exists(newFileName))
{
    //Header of the .csv File
    string clientHeader = "Client Name(ie. Billto_desc)" + "," + "Mid_id,billing number(ie billto_id)" + "," + "business unit id" + Environment.NewLine;

    File.WriteAllText(newFileName, clientHeader);
}

Although you could use other strategies, such as creating the file on startup of the application and keeping it open (using something like a StreamWriter). You would then close the writer when your application exited. This would pretty much guarantee that the file couldn't be messed with while your application is open.

You might want to do this because there is a race condition in that code - after you check the file exists, and before you write to the file, a user could delete it. Keeping the file open helps to avoid this, but you may or may not want to do it.

∞琼窗梦回ˉ 2024-09-25 18:15:11

这里的根本问题似乎是您从何处获取数据并将其附加到 CSV 文件。您的示例代码看起来像是从页面上的文本框获取各种数据,因此,如果您想要多个客户端,它们是否都会将其数据显示在屏幕上的文本框中?我的直觉可能不是。

在我看来,您应该使用某种类(可能保存在数据库中)来处理此客户端数据,然后在该类中实现一个名为 void AppendToCSV(string filename) 的方法,该方法会附加 that< /em> 客户端数据到 CSV 文件。然后,您可以循环客户端对象,依次附加每个对象。

如何生成/存储与屏幕上的文本框相关的客户端对象取决于您的应用程序想要实现的目标。

The underlying problem here seems to be where you're getting the data from to append to your CSV file. Your example code looks like it gets the various pieces of data from text boxes on the page, so if you want multiple clients, are they all going to have their data on the screen in text boxes? My instinct is probably not.

It sounds to me like you should be handling this client data using a class of some sort (perhaps persisted in a database) and then implement a method in the class called something like void AppendToCSV(string filename), which appends that client data to the CSV file. Then you can loop over your client objects, appending each one in turn.

How you produce/store your client objects, in relation to the text boxes you have on the screen, depends on what your app is trying to achieve.

怂人 2024-09-25 18:15:11

我知道这个问题已经得到解答,但我做了什么来创建订阅者的“日志”。这使用反射来获取对象的属性和值。希望这对将来的人有帮助。

 internal static bool UpdateSubscriberList(MailingListEmail subscriber)
    {
        PropertyInfo[] propertyinfo;
        propertyinfo = typeof(MailingListEmail).GetProperties();
        var values = string.Empty;
        try
        {
            string fileName = @"C:\Development\test.csv";
            if (!File.Exists(fileName))
            {

                var header = string.Empty;
                foreach (var prop in propertyinfo)
                {
                    if (string.IsNullOrEmpty(header))
                        header += prop.Name;
                    else
                        header = string.Format("{0},{1}", header, prop.Name);


                }
                header = string.Format("{0},{1}", header, "CreatedDate");
                header += Environment.NewLine;
                File.WriteAllText(fileName, header);

            }


                foreach (var prop in propertyinfo)
                {
                    var value = prop.GetValue(subscriber, null);

                    if (string.IsNullOrEmpty(values))
                        values += value;
                    else
                        values = string.Format("{0},{1}", values, value);

                }
                values = string.Format("{0},{1}", values, DateTime.Now.ToShortDateString());

                values += Environment.NewLine;
                File.AppendAllText(fileName, values);



        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return false;
        }


        return true;
    }

I know this has been answered but there is what i did to create a "log" of subscribers. This uses reflection to get the properties and values of the object. Hope this helps someone in the future.

 internal static bool UpdateSubscriberList(MailingListEmail subscriber)
    {
        PropertyInfo[] propertyinfo;
        propertyinfo = typeof(MailingListEmail).GetProperties();
        var values = string.Empty;
        try
        {
            string fileName = @"C:\Development\test.csv";
            if (!File.Exists(fileName))
            {

                var header = string.Empty;
                foreach (var prop in propertyinfo)
                {
                    if (string.IsNullOrEmpty(header))
                        header += prop.Name;
                    else
                        header = string.Format("{0},{1}", header, prop.Name);


                }
                header = string.Format("{0},{1}", header, "CreatedDate");
                header += Environment.NewLine;
                File.WriteAllText(fileName, header);

            }


                foreach (var prop in propertyinfo)
                {
                    var value = prop.GetValue(subscriber, null);

                    if (string.IsNullOrEmpty(values))
                        values += value;
                    else
                        values = string.Format("{0},{1}", values, value);

                }
                values = string.Format("{0},{1}", values, DateTime.Now.ToShortDateString());

                values += Environment.NewLine;
                File.AppendAllText(fileName, values);



        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return false;
        }


        return true;
    }
記柔刀 2024-09-25 18:15:11

这就是我所做的,它对我来说非常有效:
首先,您需要从列表视图创建数据表,或者只是从文本框中输入数据:

 `public Boolean PreparCVS(string DateOne, string DataTwo)
    {
        try
        {
        // Create the `DataTable` structure according to your data source

            DataTable table = new DataTable();
            table.Columns.Add("HeaderOne", typeof(string));
            table.Columns.Add("HeaderTwo", typeof(String));

            // Iterate through data source object and fill the table
            table.Rows.Add(HeaderOne, HeaderTwo);
            //Creat CSV File
            CreateCSVFile(table, sCsvFilePath);
            return true;
        }
        catch (Exception ex)
        {
            throw new System.Exception(ex.Message);
        }
    }`

创建数据表后,您可以通过此方法生成 CSV 文件:
在 Streamwriter 构造函数中,您必须在第二个参数中指定 True,这样您就可以将数据附加到现有的 .csv 文件中:

public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        StreamWriter sw = new StreamWriter(strFilePath, true);

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }

here is what i have done, and it works for me perfectly :
first you need to creat DataTable from your listview, or just put data from textboxes:

 `public Boolean PreparCVS(string DateOne, string DataTwo)
    {
        try
        {
        // Create the `DataTable` structure according to your data source

            DataTable table = new DataTable();
            table.Columns.Add("HeaderOne", typeof(string));
            table.Columns.Add("HeaderTwo", typeof(String));

            // Iterate through data source object and fill the table
            table.Rows.Add(HeaderOne, HeaderTwo);
            //Creat CSV File
            CreateCSVFile(table, sCsvFilePath);
            return true;
        }
        catch (Exception ex)
        {
            throw new System.Exception(ex.Message);
        }
    }`

once dataTable is created you can generate CSV file by this method :
in the streamwriter constructor you must specify in the second parameter True, by this, you can append data to you existing .csv file :

public void CreateCSVFile(DataTable dt, string strFilePath)
    {
        StreamWriter sw = new StreamWriter(strFilePath, true);

        int iColCount = dt.Columns.Count;
        for (int i = 0; i < iColCount; i++)
        {
            sw.Write(dt.Columns[i]);
            if (i < iColCount - 1)
            {
                sw.Write(",");
            }
        }
        sw.Write(sw.NewLine);

        foreach (DataRow dr in dt.Rows)
        {
            for (int i = 0; i < iColCount; i++)
            {
                if (!Convert.IsDBNull(dr[i]))
                {
                    sw.Write(dr[i].ToString());
                }
                if (i < iColCount - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);
        }
        sw.Close();
    }
白馒头 2024-09-25 18:15:11
// At first read all the data from your first CSV

StreamReader oStreamReader = new StreamReader(@"d:\test\SourceFile.csv");
string recordsFromFirstFile = oStreamReader.ReadToEnd();
oStreamReader.Close();

// Now read the new records from your another csv file
oStreamReader = new StreamReader(@"d:\test\DestinationFile.csv");
string recordsFromSecondFile = oStreamReader.ReadToEnd();
oStreamReader.Close();
oStreamReader.Dispose();

// Here Records from second file will also contain column headers so we need to truncate them using Substring() method

recordsFromSecondFile = recordsFromSecondFile.Substring(recordsFromSecondFile.IndexOf('\n') + 1);

// Now merge the records either in SourceFile.csv or in Targetfile.csv or as per your required file

StreamWriter oStreamWriter= new StreamWriter(@"d:\testdata\TargetFile.csv");
oStreamWriter.Write(recordsFromFirstFile + recordsFromSecondFile);
oStreamWriter.Close();
oStreamWriter.Dispose();

快乐编码.....

< a href="/questions/tagged/csv" class="post-tag" title="显示标记为“csv”的问题" rel="tag">csv

// At first read all the data from your first CSV

StreamReader oStreamReader = new StreamReader(@"d:\test\SourceFile.csv");
string recordsFromFirstFile = oStreamReader.ReadToEnd();
oStreamReader.Close();

// Now read the new records from your another csv file
oStreamReader = new StreamReader(@"d:\test\DestinationFile.csv");
string recordsFromSecondFile = oStreamReader.ReadToEnd();
oStreamReader.Close();
oStreamReader.Dispose();

// Here Records from second file will also contain column headers so we need to truncate them using Substring() method

recordsFromSecondFile = recordsFromSecondFile.Substring(recordsFromSecondFile.IndexOf('\n') + 1);

// Now merge the records either in SourceFile.csv or in Targetfile.csv or as per your required file

StreamWriter oStreamWriter= new StreamWriter(@"d:\testdata\TargetFile.csv");
oStreamWriter.Write(recordsFromFirstFile + recordsFromSecondFile);
oStreamWriter.Close();
oStreamWriter.Dispose();

Happy Coding.....

春夜浅 2024-09-25 18:15:11

使用 CsvHelper;

公共无效WriteDataToCsv(MsgEnvironmentData []数据,字符串csvPath)
{

   if (!File.Exists(csvPath))
   {
     using (var writer = new StreamWriter(csvPath))
     using (var csvWriter = new CsvWriter(writer,firstConfiguration))
      {

          csvWriter.WriteHeader<MsgEnvironmentData>();
          csvWriter.NextRecord();
          csvWriter.WriteRecords(data);
      }
   }
   else
   {
       using (var stream = new FileStream(csvPath, FileMode.Append))
       using (var writer = new StreamWriter(stream))
       using (var csvWriter = new CsvWriter(writer, secondConfiguration))
        {
            csvWriter.WriteRecords(data);
        }
    }

}

using CsvHelper;

public void WriteDataToCsv(MsgEnvironmentData[] data, string csvPath)
{

   if (!File.Exists(csvPath))
   {
     using (var writer = new StreamWriter(csvPath))
     using (var csvWriter = new CsvWriter(writer,firstConfiguration))
      {

          csvWriter.WriteHeader<MsgEnvironmentData>();
          csvWriter.NextRecord();
          csvWriter.WriteRecords(data);
      }
   }
   else
   {
       using (var stream = new FileStream(csvPath, FileMode.Append))
       using (var writer = new StreamWriter(stream))
       using (var csvWriter = new CsvWriter(writer, secondConfiguration))
        {
            csvWriter.WriteRecords(data);
        }
    }

}

君勿笑 2024-09-25 18:15:11

Jeramy 的答案是将内容写在最后一个单元格上,并在 csv 文件中水平排列。我将他的解决方案与给出的答案混合并匹配 此处。我知道这个问题很久以前就被问过,但对于那些进行研究的人来说,我在这里发布了答案。

string newFileName = @"C:\.NET\test.csv"; //filepath
var csv = new StringBuilder();
string clientDetails = "content1,content2,content3" + Environment.NewLine;
csv.Append(clientDetails);
File.AppendAllText(newFileName, csv.ToString());

Jeramy's answer writing the contents on last cell and from their horizontally in a row in csv file. I mixed and matched his solution with answer given here. I know this questions been asked long before but for the ones who doing research I'm posting the answer here.

string newFileName = @"C:\.NET\test.csv"; //filepath
var csv = new StringBuilder();
string clientDetails = "content1,content2,content3" + Environment.NewLine;
csv.Append(clientDetails);
File.AppendAllText(newFileName, csv.ToString());
最后的乘客 2024-09-25 18:15:11

我使用这段简单的代码将数据附加到现有的 CSV 文件:

        string[] data = { "John", "Doe", "25" };
        string csvFilePath = "example.csv";

        // Open the file for writing
        using (StreamWriter writer = File.AppendText(csvFilePath))
        {
            // Write the data row
            writer.WriteLine(string.Join(",", data));
        }

I use this simple piece of code to append data to an existing CSV file:

        string[] data = { "John", "Doe", "25" };
        string csvFilePath = "example.csv";

        // Open the file for writing
        using (StreamWriter writer = File.AppendText(csvFilePath))
        {
            // Write the data row
            writer.WriteLine(string.Join(",", data));
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文