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

查看:2744
本文介绍了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('\n');

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.

欣赏帮助,

Shaw

推荐答案

>

根据此 Microsoft文档,错误是因为大写字ID显示为第一行。将其更改为id,它会按预期工作。

According to this Microsoft Documentation, the error is shown because of the uppercase word "ID" as first row. Change it to "id" and it works as expected.

但是是的!

也尝试通过使用文件对象减少文件访问。

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

下面工作完美。

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


public class CSV {
    public static void main(String[]args) throws FileNotFoundException{
        PrintWriter pw = 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');

        pw.write(sb.toString());
        pw.close();
        System.out.println("done!");
    }
}

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

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