昨天在做Excel导出的时候,用了项目组的excel导出组件,结果搞来搞去就是无法生成Excel文件,郁闷之下自己写了一个方法和大家分享一下,不过代码写的可能有点死,欢迎大家批评指正!
public void exportToExcel() {
try {
ArrayList list = this.getSelectedCourseStudentsTableData();
System.out.println("=============size:" + list.size());
if (list != null && list.size() > 0) {
Long tp = new Long(System.currentTimeMillis());
String path = getApplicationBean().getFilePath()//设置生成文件的路径和名称
+ "printfiles/" + tp.toString() + ".xls";
String name=path.substring(path.lastIndexOf('/'),path.length());
OutputStream outf = new FileOutputStream(path);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("StudentCource");
sheet.setHorizontallyCenter(true);
HSSFRow row1 = sheet.createRow(0);
HSSFCell cell1 = row1.createCell((short) 0);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);// 设置编码
cell1.setCellValue("学号");
cell1 = row1.createCell((short) 1);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("姓名");
cell1 = row1.createCell((short) 2);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("性别");
cell1 = row1.createCell((short) 3);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("学生类别");
cell1 = row1.createCell((short) 4);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("年级");
cell1 = row1.createCell((short) 5);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("所属学院");
cell1 = row1.createCell((short) 6);
cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
cell1.setCellValue("所学专业");
ArrayList selectedCourseStudentslist = this
.getSelectedCourseStudentsTableData();
for (int i = 0; i < selectedCourseStudentslist.size(); i++) {
HSSFRow row = sheet.createRow(i+1);
PgtStatusInfo pgtStatusInfo = (PgtStatusInfo) selectedCourseStudentslist
.get(i);
HSSFCell cell = row.createCell((short) 0);
cell.setCellValue(pgtStatusInfo.getStudentNo());
cell = row.createCell((short) 1);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);// 设置编码
cell.setCellValue(pgtStatusInfo.getName());
cell = row.createCell((short) 2);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(pgtStatusInfo.getSexCn());
cell = row.createCell((short) 3);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(pgtStatusInfo.getPgtTypeCn());
cell = row.createCell((short) 4);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(pgtStatusInfo.getGradeCn());
cell = row.createCell((short) 5);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(pgtStatusInfo.getBelongDeptCn());
cell = row.createCell((short) 6);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(pgtStatusInfo.getSpeCn());
}
wb.write(outf);
outf.close();
this.excelLink ="./files/printfiles/" + name;
this.excelFileLinkVisible = true;
this.outputFileLinkVisible = false;
} else {
getApplicationBean().addMessage(FacesMessage.SEVERITY_INFO,
"导出excel内容为空!", null);
}
} catch (Exception e) {
getApplicationBean().addMessage(FacesMessage.SEVERITY_ERROR,
"导出excel操作失败!", e.getMessage());
}
}