我正在尝试使用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();
我是否需要在java中使用某些库才能打印到csv文件?我认为只要你使用了正确的格式,你就可以在java中本地执行此操作。
感谢帮助,
肖
答案 0 :(得分:78)
基本上是因为MS Excel无法决定如何打开包含此类内容的文件。
当您将ID
作为电子表格类型文件中的第一个字符时,它会匹配SYLK文件的规范,而MS Excel(以及可能的其他电子表格应用程序)会尝试将其作为SYLK打开文件。但与此同时,它不符合SYLK文件的完整规范,因为文件中的其余值是逗号分隔的。因此,显示错误。
要解决此问题,请将"ID"
更改为"id"
,它应该按预期工作。
这很奇怪。但是,是的!
还尝试使用较少的文件对象来最小化文件访问。
我测试了,下面的代码非常完美。
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());
}
}
}
答案 1 :(得分:9)
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!");
}
}
答案 2 :(得分:0)
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();
答案 3 :(得分:0)
我认为这是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.");
}
}
答案 4 :(得分:0)
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();
}
}
答案 5 :(得分:0)
如果您希望在每次重新运行程序时都覆盖文件,则此问题的答案很好,但是如果希望在运行时不丢失记录,则可以尝试使用此方法
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();
}
}
答案 6 :(得分:0)
我看到您已经有了答案,但这是另一个答案,甚至可能更快 一个简单的类,用于传递对象列表并检索csv或excel或受密码保护的zip csv或excel。 https://github.com/ernst223/spread-sheet-exporter
SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
File fileCSV = spreadSheetExporter.getCSV();
答案 7 :(得分:0)
Generate CSV file from List of Objects
Finally, following is an example showing how to generate a CSV file from List of objects. The example uses the MyUser class defined in the previous section -
import com.opencsv.CSVWriter;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class OpenCSVWriter {
private static final String STRING_ARRAY_SAMPLE = "./example.csv";
public static void main(String[] args) throws IOException,
CsvDataTypeMismatchException,
CsvRequiredFieldEmptyException {
try ( Writer writer = Files.newBufferedWriter(Paths.get(STRING_ARRAY_SAMPLE));
) {
StatefulBeanToCsv<MyUser> beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
List<MyUser> myUsers = new ArrayList<>();
myUsers.add(new MyUser("Sundar Pichai ♥", "sundar.pichai@gmail.com", "+1-1111111111", "India"));
myUsers.add(new MyUser("Satya Nadella", "satya.nadella@outlook.com", "+1-`enter code here`1111111112", "India"));
beanToCsv.write(myUsers);
}
}
}