Java - 将字符串写入 CSV 文件 [英] Java - Writing strings to a CSV file

查看:77
本文介绍了Java - 将字符串写入 CSV 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

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

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

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.

感谢帮助,

推荐答案

基本上是因为 MS Excel 无法决定如何打开具有此类内容的文件.

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

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

When you put ID as the first character in a Spreadsheet type file, it matches the specification of a SYLK file and MS Excel (and potentially other Spreadsheet Apps) try 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" 更改为 id",它应该会按预期工作.

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

这很奇怪.但是,是的!

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("test.csv")) {

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

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

      writer.write(sb.toString());

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

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

  }
}

这篇关于Java - 将字符串写入 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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