/这是个响应请求的方法
@RequestMapping(method = RequestMethod.GET, value = "testResponseExportXLS")
public void testResponseExportXLS(HttpServletRequest request,HttpServletResponse response) {
try {
exportXLSfromMaps("exportTest",response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/具体实现方法如下:
public void exportXLSfromMaps(String fileName, HttpServletResponse response)
throws Exception {
downloadFile(fileName + ".xls",response);
java.io.OutputStream out = response.getOutputStream();
WritableWorkbook workbook = null;
WritableSheet sheet=null;
workbook = Workbook.createWorkbook(out);
sheet = workbook.createSheet("test Sheet", 0);
// 添加label对象
Label labelC = new Label(0, 0, "aaa");
sheet.addCell(labelC);
// 添加带有字型Formatting的对象
WritableFont wf = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, true);
WritableCellFormat wcfF = new WritableCellFormat(wf);
jxl.write.Label labelCF = new jxl.write.Label(1, 0,"bbb", wcfF);
sheet.addCell(labelCF);
// 添加带有字体颜色Formatting的对象
WritableFont wfc = new WritableFont(WritableFont.ARIAL, 10, WritableFont.NO_BOLD, false,UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.RED);
WritableCellFormat wcfFC = new WritableCellFormat(wfc);
wcfFC.setAlignment(jxl.format.Alignment.CENTRE);
Label labelCFC = new Label(2, 0,"ccc", wcfFC);
sheet.addCell(labelCFC);
sheet.mergeCells(0,0,0,1);
sheet.mergeCells(2,0,3,0);
// 添加带有字体颜色Formatting的对象
WritableFont wf1 = new WritableFont(WritableFont.TIMES, 11, WritableFont.BOLD, true);
WritableCellFormat wcfFC1 = new WritableCellFormat(wf1);
Label labelCFC1 = new Label(3, 0,"ddd", wcfFC1);
sheet.addCell(labelCFC1);
// 2.添加Number对象
jxl.write.Number labelN = new jxl.write.Number(0, 1, 12345);
sheet.addCell(labelN);
Label labelCFC2 = new Label(1, 1,"eee");
sheet.addCell(labelCFC2);
Label labelCFC3 = new Label(2, 1,"fff");
sheet.addCell(labelCFC3);
Label labelCFC4 = new Label(3, 1,"ggg");
sheet.addCell(labelCFC4);
workbook.write();
workbook.close();
out.flush();
out.close();
}
public void initAttachmentHeader(HttpServletResponse response)
{
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-Type", "application/force-download");
response.setHeader("Content-Type", "application/octet-stream");
response.setHeader("Content-Type", "application/download");
response.setHeader("Cache-Control", "private, max-age=0, must-revalidate");
response.setHeader("Pragma", "public");
}
public void downloadFile(String fileName,HttpServletResponse response)
{
downloadFile(fileName, Const.nullInt,response);
}
public void downloadFile(String fileName, long length,HttpServletResponse response)
{
initAttachmentHeader(response);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
if(length != (long)Const.nullInt)
response.setHeader("Content-Length", String.valueOf(length));
}