62,614
社区成员
发帖
与我相关
我的任务
分享
//导出pdf按钮
//导出word按钮
@FXML
private void handleWordExport() {
int selectedIndex = studentTable.getSelectionModel().getSelectedIndex();
Student selectedStudent = studentTable.getSelectionModel().getSelectedItem();
if(selectedIndex >= 0) {
//只有在选中一个学生的时候才会导出
//你只看这一点就行,这一点和下面对应
WordTest test = new WordTest(selectedStudent);
test.createWord();
}else {
Alert alert = new Alert(AlertType.ERROR);
alert.setTitle("导出失败");
alert.setHeaderText("没有学生可以选择");
alert.setContentText("请选择一个学生");
alert.showAndWait();
}
}
//导出word类和方法
public class WordTest {
private Configuration configuration = null;
Student student;
public WordTest(Student selectedStudent){
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
configuration.setEncoding(Locale.getDefault(), "utf-8");
//创建一个Configuration实例 的后面给这个对象设置编码为utf-8:
this.student = selectedStudent;
}
public void createWord(){
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap);
configuration.setClassForTemplateLoading(this.getClass(), "/Student/model");//模板文件所在路径
Template t = null;
try {
t = configuration.getTemplate("exportModel.ftl"); //获取模板文件
System.out.println("获取模板文件成功");
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("E:/outFile/"+student.getName()+"的资料.doc"); //导出文件
System.out.println("导出位置为E:/outFile");
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
//关闭流
out.flush();
out.close();
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("导出成功");
}
//填充数据
private void getData(Map<String, Object> dataMap) {
dataMap.put("Name", student.getName());
dataMap.put("Photo", student.getPhoto());
dataMap.put("Id", student.getid());
dataMap.put("Class", student.getClassIn());
dataMap.put("Chinese", student.getChinese());
dataMap.put("Math", student.getMath());
dataMap.put("English", student.getEnglish());
dataMap.put("Physics", student.getphysics());
dataMap.put("Chemistry", student.getchemistry());
dataMap.put("biology", student.getbiology());
}
}