Java - 将字符串写入 CSV 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30073980/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 09:04:35  来源:igfitidea点击:

Java - Writing strings to a CSV file

javaexcelcsvexport-to-csv

提问by Shaw

I am trying to write data to a csv file with java, however when I try opening the produced file with excel I am getting an error saying the file is corrupt. Upon opening the file in notepad it looks to be formatted correctly so I'm not sure what the issue is. I am using the FileWriter class to output the data to the file.

我正在尝试使用 java 将数据写入 csv 文件,但是当我尝试使用 excel 打开生成的文件时,我收到一条错误消息,指出该文件已损坏。在记事本中打开文件后,它看起来格式正确,所以我不确定问题是什么。我正在使用 FileWriter 类将数据输出到文件。

FileWriter writer = new FileWriter("test.csv");

writer.append("ID");
writer.append(',');
writer.append("name");
writer.append(',');
...
writer.append('\n');

writer.flush();
writer.close();

Do I need to use some library in java in order to print to a csv file? I presumed you could just do this natively in java as long as you used the correct formatting.

我是否需要在 java 中使用一些库才能打印到 csv 文件?我认为只要您使用正确的格式,您就可以在 Java 中本地执行此操作。

Appreciate the help,

感谢帮助,

Shaw

采纳答案by Prashant Ghimire

Basically it's because MS Excel can't decide how to open the file with such content.

基本上是因为 MS Excel 无法决定如何打开包含此类内容的文件。

When you put IDas the first character in a Spreadsheet type file, it matches the specification of a SYLKfile and MS Excel (and potentially other Spreadsheet Apps) tries to open it as a SYLK file. But at the same time, it does not meet the complete specification of a SYLK file since rest of the values in the file are comma separated. Hence, the error is shown.

当您将ID电子表格类型文件作为第一个字符放入时,它与SYLK文件的规范相匹配,并且 MS Excel(以及可能的其他电子表格应用程序)尝试将其作为 SYLK 文件打开。但同时,它不符合 SYLK 文件的完整规范,因为文件中的其余值是用逗号分隔的。因此,显示错误。

To solve the issue, change "ID"to "id"and it should work as expected.

要解决此问题,请更改"ID""id"并且它应该按预期工作。

enter image description here

在此处输入图片说明

This is weird. But, yeah!

这很奇怪。但是,是的!

Also trying to minimize file access by using file object less.

还试图通过减少使用文件对象来最小化文件访问。

I tested and the code below works perfect.

我测试过,下面的代码完美无缺。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvWriter {
  public static void main(String[] args) {

    try (PrintWriter writer = new PrintWriter(new File("test.csv"))) {

      StringBuilder sb = new StringBuilder();
      sb.append("id,");
      sb.append(',');
      sb.append("Name");
      sb.append('\n');

      sb.append("1");
      sb.append(',');
      sb.append("Prashant Ghimire");
      sb.append('\n');

      writer.write(sb.toString());

      System.out.println("done!");

    } catch (FileNotFoundException e) {
      System.out.println(e.getMessage());
    }

  }
}

回答by Tamil veera Cholan

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

public class CsvFile {

    public static void main(String[]args){
        PrintWriter pw = null;
        try {
            pw = new PrintWriter(new File("NewData.csv"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        StringBuilder builder = new StringBuilder();
        String columnNamesList = "Id,Name";
        // No need give the headers Like: id, Name on builder.append
        builder.append(columnNamesList +"\n");
        builder.append("1"+",");
        builder.append("Chola");
        builder.append('\n');
        pw.write(builder.toString());
        pw.close();
        System.out.println("done!");
    }
}

回答by Somuchandra

    String filepath="/tmp/employee.csv";
    FileWriter sw = new FileWriter(new File(filepath));
    CSVWriter writer = new CSVWriter(sw);
    writer.writeAll(allRows);

    String[] header= new String[]{"ErrorMessage"};
    writer.writeNext(header);

    List<String[]> errorData = new ArrayList<String[]>();
    for(int i=0;i<1;i++){
        String[] data = new String[]{"ErrorMessage"+i};
        errorData.add(data);
    }
    writer.writeAll(errorData);

    writer.close();

回答by Samim Aktar

I think this is a simple code in java which will show the string value in CSV after compile this code.

我认为这是 Java 中的一个简单代码,它会在编译此代码后以 CSV 格式显示字符串值。

public class CsvWriter {

    public static void main(String args[]) {
        // File input path
        System.out.println("Starting....");
        File file = new File("/home/Desktop/test/output.csv");
        try {
            FileWriter output = new FileWriter(file);
            CSVWriter write = new CSVWriter(output);

            // Header column value
            String[] header = { "ID", "Name", "Address", "Phone Number" };
            write.writeNext(header);
            // Value
            String[] data1 = { "1", "First Name", "Address1", "12345" };
            write.writeNext(data1);
            String[] data2 = { "2", "Second Name", "Address2", "123456" };
            write.writeNext(data2);
            String[] data3 = { "3", "Third Name", "Address3", "1234567" };
            write.writeNext(data3);
            write.close();
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();

        }

        System.out.println("End.");

    }
}

回答by anil084

 private static final String FILE_HEADER ="meter_Number,latestDate";
    private static final String COMMA_DELIMITER = ",";
    private static final String NEW_LINE_SEPARATOR = "\n";
    static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:m m:ss");

    private void writeToCsv(Map<String, Date> meterMap) {
        try {
            Iterator<Map.Entry<String, Date>> iter = meterMap.entrySet().iterator();
            FileWriter fw = new FileWriter("smaple.csv");
            fw.append(FILE_HEADER.toString());
            fw.append(NEW_LINE_SEPARATOR);
            while (iter.hasNext()) {
                Map.Entry<String, Date> entry = iter.next();
                try {
                    fw.append(entry.getKey());
                    fw.append(COMMA_DELIMITER);
                    fw.append(formatter.format(entry.getValue()));
                    fw.append(NEW_LINE_SEPARATOR);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    iter.remove();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

回答by Justice Bringer

Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunningyour program, you may want to try this

如果您想在每次重新运行程序时覆盖您的文件,则此问题的答案很好,但是如果您希望在重新运行程序时不丢失记录,您可能想试试这个

public void writeAudit(String actionName) {
    String whereWrite = "./csvFiles/audit.csv";

    try {
        FileWriter fw = new FileWriter(whereWrite, true);
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw);

        Date date = new Date();

        pw.println(actionName + "," + date.toString());
        pw.flush();
        pw.close();

    } catch (FileNotFoundException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    }
}