使用C#插入\update .csv文件 [英] Insert\update .csv file using C#

查看:117
本文介绍了使用C#插入\update .csv文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用C#在.csv文件中插入和/或更新记录。我有3个文本框,我必须在文件中插入(将插入3个不同的列)。我提到了 https://stackoverflow.com/questions/14370757/editing-saving-a-row-in-a-csv-file 来更新.csv文件,但记录是根本不插入或更新。

我有3个条件要检查:

1.如果.csv文件为空,则插入记录。

2.如果记录不然后插入新记录。

3.如果记录存在则更新记录。



我要插入的3列是

1. ID(字符串)

2.批号(字符串)

3.位置(字符串)



我尝试过:



I am trying to Insert and/or update record in .csv file using C#. I have 3 text box that I have to insert in file (which will be inserted in 3 different columns). I referred https://stackoverflow.com/questions/14370757/editing-saving-a-row-in-a-csv-file to update in .csv file but the record is not inserting or updating at all.
I have 3 conditions to check:
1. If .csv file is empty then insert the record.
2. If record does not exist then insert new record.
3. If record exist then update record.

3 columns I want to insert is
1. ID (string)
2. Batch Number (string)
3. Location (string)

What I have tried:

String path = @"\Loc.csv";
List<String> lines = new List<String>();

if (File.Exists(path));
{
    using (StreamReader reader = new StreamReader(path))
    {
        String line;

        while ((line = reader.ReadLine()) != null)
        {
            if (line.Contains(","))
            {
                String[] split = line.Split(',');

                if (split[1].Contains(txtID.text))
                {
                    split[2] = txtBatch.text;
                    split[3] = txtLoc.text;                    
                }
            }

            lines.Add(line);
        }
    }

    using (StreamWriter writer = new StreamWriter(path, false))
    {
        foreach (String line in lines)
            writer.WriteLine(line);
    }
}





最初文件为空。那么如何执行插入/更新操作?



Initially file is empty. So How I can perform Insert/Update operation?

推荐答案

创建一个封装此数据并管理文件的类。当你在类上调用Save方法时,或者在对数据进行每次操作之后,它应该管理内存中的数据并重写文件。



当你创建一个该类的实例,传入它应该管理的文件名。



然后该类应该加载该文件中的数据(如果存在)。如果没有,请不要做任何事情。



该类应公开操作数据的方法,如插入,更新,删除和管理数据一组数据记录(另一个类!)。



当需要将文件写回来时,枚举你的集合并用你的文件覆盖那里的文件数据格式为CSV。
Create a class that encapsulates this data and manages the file. It should manage the data in memory and rewrite the file when you either call a Save method on the class, or after each operation on the data.

When you create an instance of the class, pass in the filename it's supposed to manage.

The class should then load the data from that file, if it exists. If it doesn't, don't do anything.

The class should expose methods to manipulate the data, like insert, update, delete, and managed that data in a collection of data records (another class!).

When the time comes to write the file back out, enumerate over your collection and overwrite the file that's there with the data formatted as CSV.


首先,请阅读:为什么要建立自己的CSV解析器(或许不是) [ ^ ]



处理csv数据的正确方法是使用:

1.类(通过 Dave Kreskoviak [ ^ ])然后你就可以阅读,写数据了

2. ADO.NET - OleDb



请查看过去的答案:

处理大型网络的最佳方式大量的CSV数据? [ ^ ]

用C#读取和写入CSV文件 [ ^ ]

如何:在Visual Basic中读取逗号分隔的文本文件Microsoft Docs [ ^ ]
First of all, please read this: Why to build your own CSV parser (or maybe not)[^]

A proper way to deal with csv data is to use:
1. classes (see solution #1 by Dave Kreskoviak[^]) then you'll be able read, write data
2. ADO.NET - OleDb

Please, see past answers:
Best way to process large amounts of CSV data?[^]
Reading and Writing CSV Files in C#[^]
How to: read from comma-delimited text files in Visual Basic | Microsoft Docs[^]


有许多excel阅读器和编写器开源dll可用像EPPLUS,NPOI。

这里是我在我的一个项目中开发的代码示例,它更专注于读取数据,但是你有很多功能可以将数据写入单个单元格以及需要探索它。一点。该DLL不需要MS Office安装在服务器上,因为它是开源的。

There are many excel reader and writer open source dlls available like EPPLUS, NPOI.
here is example of code I have developed in one of my project, it is more focusing on reading data but you have plenty of features to write data into individual cell as well just need to explore it. little bit. The dll does not require MS office to be installed on server as it is open source.
#region Read xlsx file
                  using (ExcelPackage package = new ExcelPackage())
                  {

                      package.Load(stream);
                      if (package.Workbook.Worksheets.Count > 1 && ReaderRequestEntity.firsttimeread == true)
                      {

                          foreach (var item in package.Workbook.Worksheets)
                          {
                              ReaderRequestEntity.SheetNamesList.Add(item.Name);
                          }
                      }
                      if (package.Workbook.Worksheets.Count == 0)
                          ReaderRequestEntity.Message = "Your Excel file does not contain any work sheets";
                      else
                      {
                          ExcelWorksheet workSheet = package.Workbook.Worksheets.First();

                          int EndColumn = workSheet.Dimension.End.Column > 50 ? 50 : workSheet.Dimension.End.Column;
                          foreach (var firstRowCell in workSheet.Cells[ReaderRequestEntity.HeaderRowNo, 1, ReaderRequestEntity.HeaderRowNo, EndColumn])
                          {
                              if (ReaderRequestEntity.firsttimeread != true && (firstRowCell.Text == null || firstRowCell.Text == ""))
                                  continue;
                              else
                                  table.Columns.Add(firstRowCell.Text);
                          }
                          for (var rowNumber = ReaderRequestEntity.HeaderRowNo; rowNumber <= workSheet.Dimension.End.Row; rowNumber++)
                          {
                              if (!ReaderRequestEntity.RowsTobeIngonredList.Contains(rowNumber.ToString()))
                              {
                                  int endcolumn = (ReaderRequestEntity.firsttimeread == true ? EndColumn : table.Columns.Count);

                                  var row = workSheet.Cells[rowNumber, 1, rowNumber, endcolumn];
                                  var newRow = table.NewRow();
                                  int j = 0;
                                  foreach (var cell in row)
                                  {
                                      try
                                      {
                                          newRow[j] = cell.Text;
                                          j++;
                                      }
                                      catch (Exception ex)
                                      {
                                          if (ex.Message.Contains("Cannot find column"))
                                          {
                                              table.Columns.Add("column" + j);
                                          }
                                      }
                                  }
                                  try
                                  {
                                      table.Rows.Add(newRow);
                                  }
                                  catch (Exception)
                                  {
                                      throw;
                                  }
                              }
                          }
                      }
                  }
                  #endregion




private void formatCellValue(ref ExcelWorksheet worksheet)
{
    DataTable dtColumnMapping = (DataTable)HttpContext.Current.Session["ColumnMappingTable"];
    int i = 0;
    foreach (DataRow item in dtColumnMapping.Rows)
    {
        if (item["Dbcolumntype"].ToString() == "date")
            worksheet.Column(i).Style.Numberformat.Format = "yyyy-mm-dd";
        i++;
    }
}

public int Calculatewidth(string firstRowCell)
{
    switch (firstRowCell.Length)
    {
        case 1 - 5:
            {
                return 75;
            }
        case 6 - 9:
            {
                return 120;
            }
        default:
            return 140;
    }
}



你可以在dev plex上得到相同的例子。


You can get very good example for the same at dev plex.


这篇关于使用C#插入\update .csv文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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