参考代码
/**
* 导出CSV格式的
* @return
*/
@POST
@Path("/subjectExportCSV")
@Produces("*/*")
public String subjectExportCSV(){
List<Subject> listSubjectAll = subjectService.listSubjectAll();
List<SubjectSearchModel> searchModels = searchModelList(listSubjectAll);
String path = this.getClass().getResource("/").getPath();// 得到d:/tomcat/webapps/工程名WEB-INF/classes/路径
path = path.substring(1, path.indexOf("WEB-INF/classes"));// 从路径字符串中取出工程路劲
FileOutputStream out;
try {
//查询所有年级的列表
/*List<Subject> listSubjectAll = subjectService.listSubjectAll();
CsvWriter wr =new CsvWriter("D://subject.csv",',',Charset.forName("GBK"));
for(Subject s : listSubjectAll){
String[] contents = {s.getId()+"",s.getName()+"",s.getCode()+"",s.getDeleteFlag()+"",s.getRemark()+"",s.getCreateUserId()+"",s.getCreateDate()+"",s.getUpdateUserId()+"",s.getUpdateDate()+""};
wr.writeRecord(contents);
}
wr.close();*/
File csvFile = null;
csvFile = new File(path+"make/csvprint/subject.csv");
System.out.println(path+"make/csvprint/subject.csv");
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists()) {//假如目录../make/csvprint不存在则创建目录
parent.mkdirs();
}
csvFile.createNewFile();//创建一个空文件
out = new FileOutputStream(csvFile);//用已经打开的文件创建一个新的文件流
OutputStreamWriter osw = new OutputStreamWriter(out, "GB2312");//是Writer的子类,将输出的字符流变为字节流,即将一个字符流的输出对象变为字节流输出对象。
BufferedWriter bw = new BufferedWriter(osw);
bw.write("科目名称" + "," +"科目代号" + ","+"备注" +"\r\n");
for (int i = 0; i < searchModels.size(); i++) {
String name = searchModels.get(i).getName().replaceAll(",", "").replaceAll(",", "");
String code=searchModels.get(i).getCode().replaceAll(",", "").replaceAll(",", "");
String remark=searchModels.get(i).getRemark().replaceAll(",", "").replaceAll(",", "");
bw.write(name + ","+code+","+remark+ "\r\n");
}
bw.close();
osw.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
return StringParam.returnPageFalse();
}
return StringParam.returnPageTrue("path","subject.csv");
}