我正在寻找关于如何处理正在创建的csv文件的建议,然后由我们的客户上传,并且可能在值中有逗号,如公司名称。

我们正在考虑的一些想法是:带引号的标识符(value "," values ","等等)或使用|代替逗号。最大的问题是我们必须让它变得简单,否则客户就不会这么做。


当前回答

在字符串周围加双引号。这就是Excel所做的。

阿拉伊莱,

将双引号转义为2 双引号。如。 “test1”、“foo”“酒吧”,“test2”

其他回答

我发现的最简单的解决方案是LibreOffice使用的:

替换所有“by”字面值 在字符串周围加上双引号

你也可以使用Excel使用的:

替换所有字面的" by " 在字符串周围加上双引号

注意,其他人建议只执行上面的第2步,但这对于“后面跟着一个,”的行不起作用,就像在CSV中,你想要有一个字符串hello”,world的单列,因为CSV会这样读:

"hello",world"

它被解释为有两列的行:hello和world"

在字符串周围加双引号。这就是Excel所做的。

阿拉伊莱,

将双引号转义为2 双引号。如。 “test1”、“foo”“酒吧”,“test2”

我使用papaParse库来解析CSV文件,并拥有键-值对(键/头/ CSV文件-值的第一行)。

下面是我举的例子:

https://codesandbox.io/embed/llqmrp96pm

它有一个dummy.csv文件来演示CSV解析。

我在reactJS中使用过它,尽管它很容易在任何语言编写的应用程序中复制。

您可以像这样读取csv文件。

这利用了分割和空格。

ArrayList List = new ArrayList();
static ServerSocket Server;
static Socket socket;
static ArrayList<Object> list = new ArrayList<Object>();


public static void ReadFromXcel() throws FileNotFoundException
{   
    File f = new File("Book.csv");
    Scanner in = new Scanner(f);
    int count  =0;
    String[] date;
    String[] name;
    String[] Temp = new String[10];
    String[] Temp2 = new String[10];
    String[] numbers;
    ArrayList<String[]> List = new ArrayList<String[]>();
    HashMap m = new HashMap();

         in.nextLine();
         date = in.nextLine().split(",");
         name = in.nextLine().split(",");
         numbers = in.nextLine().split(",");
         while(in.hasNext())
         {
             String[] one = in.nextLine().split(",");
             List.add(one);
         }
         int xount = 0;
         //Making sure the lines don't start with a blank
         for(int y = 0; y<= date.length-1; y++)
         {
             if(!date[y].equals(""))
             {   
                 Temp[xount] = date[y];
                 Temp2[xount] = name[y];
                 xount++;
             }
         }

         date = Temp;
         name =Temp2;
         int counter = 0;
         while(counter < List.size())
         {
             String[] list = List.get(counter);
             String sNo = list[0];
             String Surname = list[1];
             String Name = list[2];
             for(int x = 3; x < list.length; x++)
             {           
                 m.put(numbers[x], list[x]);
             }
            Object newOne = new newOne(sNo, Name, Surname, m, false);
             StudentList.add(s);
             System.out.println(s.sNo);
             counter++;
         }

CSV格式使用逗号分隔值,包含回车、换行、逗号或双引号的值用双引号括起来。包含双引号的值会被引用,并且每个文字引号都被紧挨着的前引号转义:例如,以下3个值:

test
list, of, items
"go" he said

将被编码为:

test
"list, of, items"
"""go"" he said"

任何字段都可以加引号,但只有包含逗号、CR/NL或引号的字段必须加引号。

CSV格式没有真正的标准,但几乎所有应用程序都遵循这里记录的约定。在其他地方提到的RFC不是CSV的标准,它是一个用于在MIME中使用CSV的RFC,它包含了一些非常规的和不必要的限制,使它在MIME之外无用。

我所见过的许多CSV模块不适应的一个问题是,可以在单个字段中编码多行,这意味着您不能假设每一行都是一个单独的记录,您要么需要不允许数据中出现换行,要么准备好处理这个问题。