The following code generation csv file, use the pop-up calculator Microsoft Execl successfully, although there are safety tips when open, but most will still receive such vulnerability src
--------------------------------------------------------------------------------------------
package jinqi;
public class User {
private String username;
private String password;
private int age;
private String name;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String username, String password, String name, int age) {
super();
this.username = username;
this.password = password;
this.age = age;
this.name = name;
}
}
--------------------------------------------------------------------------------
package jinqi;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
public class Test {
private static final String NEW_LINE_SEPARATOR = "\n";
//CSV文件头
private static final Object [] FILE_HEADER = {"用户名","密码","名称","年龄"};
/**
* 写CSV文件
*
* @param fileName
*/
public static void writeCsvFile(String fileName) {
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
//创建 CSVFormat
CsvFileFormat = CSVFormat.DEFAULT.withRecordSeparator CSVFormat (NEW_LINE_SEPARATOR);
the try {
// Initialization FileWriter
FileWriter FileWriter new new = (fileName);
// initialize CSVPrinter
csvFilePrinter = new new CSVPrinter (FileWriter, csvFileFormat);
// create a CSV file header
csvFilePrinter.printRecord ( FILE_HEADER);
// user objects in List
List <the user> = new new userList the ArrayList <the user> ();
userList.add (the user new new ( "zhangsan", "+ = 2. 7", "San", 25)) ;
userList.add (the User new new ( "Lisi", "! = cmd | '/ C Calc.exe' Z0 of", "John Doe", 23 is));
userList.add (the User new new ( "wangwu","456", "王五", 24));
userList.add(new User("zhaoliu", "zhaoliu", "赵六", 20));
// 遍历List写入CSV
for (User user : userList) {
List<String> userDataRecord = new ArrayList<String>();
userDataRecord.add(user.getUsername());
userDataRecord.add(user.getPassword());
userDataRecord.add(user.getName());
userDataRecord.add(String.valueOf(user.getAge()));
csvFilePrinter.printRecord(userDataRecord);
}
System.out.println("CSV文件创建成功~~~");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileWriter.flush();
fileWriter.close();
csvFilePrinter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* @param args
*/
public static void main(String[] args){
writeCsvFile("G:\\jinqi.csv");
}
}