Java下载创建好的Excel模板

java

1.废话不多说,直接上源码

//从数据库取数据创建表格	
private HSSFWorkbook exportStudentInfo(List<ExamStudentVo> studentList, List<ExamStudentVo> subjectName,

Integer testId) {

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheetlist = wb.createSheet();

sheetlist.protectSheet(Constant.EXCEL_LOCK_PASSWORD);

HSSFRow row1 = sheetlist.createRow(0);

row1.createCell(0).setCellValue(Constant.EXCEL_ID);// 身份标识

row1.createCell(1).setCellValue(testId);

HSSFRow row2 = sheetlist.createRow(1);

sheetlist.setColumnWidth(3, 15 * 256);// 设置宽度

sheetlist.setColumnWidth(4, 12 * 256);

row1.setZeroHeight(true);// 隐藏行

sheetlist.setColumnHidden(1, true);// 隐藏列

org.apache.poi.hssf.usermodel.HSSFCellStyle unLockCellStyle = wb.createCellStyle();

unLockCellStyle.setLocked(false);

row2.createCell(0).setCellValue("序号");

row2.createCell(1).setCellValue("学生ID");

row2.createCell(2).setCellValue("姓名");

row2.createCell(3).setCellValue("年级");

row2.createCell(4).setCellValue("班级");

int t = 5;

for (int i = 0; i < subjectName.size(); ++i) {

row1.createCell(t).setCellValue(subjectName.get(i).getSubjectId());

row2.createCell(t).setCellValue(subjectName.get(i).getSubjectName());

t++;

}

int temRow = 2;

for (int i = 0; i < studentList.size(); ++i) {

HSSFRow row3 = sheetlist.createRow(temRow);

if (StringUtil.isNullOrEmpty(studentList.get(i))) {

continue;

}

row3.createCell(0).setCellValue(i + 1);

row3.createCell(1).setCellValue(studentList.get(i).getStudentId());

row3.createCell(2).setCellValue(studentList.get(i).getStudentName());

row3.createCell(3)

.setCellValue(studentList.get(i).getStageName() + "部" + studentList.get(i).getEntranceYear() + "级");

row3.createCell(4).setCellValue(studentList.get(i).getClassName());

temRow++;

int tem = 5;

for (int j = 0; j < subjectName.size(); ++j) {

row3.createCell(tem).setCellValue(HSSFCell.CELL_TYPE_STRING);

row3.createCell(tem).setCellStyle(unLockCellStyle);

tem++;

}

}

return wb;

}

 2.下载

              HSSFWorkbook wb = importScoreService.exportTestInfo(eq.getTestId());

String testName = importScoreService.getTestName(eq.getTestId());

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

wb.write(byteArrayOutputStream);

testName = StringUtils.deleteWhitespace(testName);

String dateTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmm");

//设置文件标题

String outFile = "学生成绩/" + dateTime +"/" + testName + ".xls";

response.setContentType("application/vnd.ms-excel;charset=utf-8");

//对文件名编码

outFile = response.encodeURL(new String(outFile.getBytes("gb2312"), "iso8859-1"));

//使用Servlet实现文件下载的时候,避免浏览器自动打开文件

response.addHeader("Content-Disposition", "attachment;filename=" + outFile);

//将流写进response输出流中

ServletOutputStream outputstream = response.getOutputStream();

byteArrayOutputStream.writeTo(outputstream);

byteArrayOutputStream.close();

outputstream.flush();

 3.下载完毕

以上是 Java下载创建好的Excel模板 的全部内容, 来源链接: utcz.com/z/394889.html

回到顶部