原文来源:http://blog.sina.com.cn/s/blog_758084f801016ijn.html
[size=large][size=medium]
@RequestMapping(params="method=exportWord")
protected ModelAndView onSubmit(ModelMap modelMap,HttpServletRequest request,
HttpServletResponse response, HttpSession session)
throws Exception {
String checkDate=request.getParameter("checkDate");
OutputStream os = null;
String fileName=Calendar.getInstance().getTimeInMillis()+".doc";
response.setContentType("application/msword");
response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode(fileName, "UTF-8"));
InputStream inputStream =this.getWordFile(list);
os = response.getOutputStream();
byte[] b = new byte[10240];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
os.flush();
os.close();
inputStream.close();
return null;
}
public InputStream getWordFile() throws Exception{
Document doc=new Document(PageSize.A4);//创建DOC
ByteArrayOutputStream byteArrayOut=new ByteArrayOutputStream();//创建新字节输出流
RtfWriter2.getInstance(doc, byteArrayOut);//建立一个书写器与document对象关联,通过书写器可以将文档写入到输出流中
doc.open();//打开文档
RtfFont titleFont=new RtfFont("宋体", 14, Font.NORMAL, Color.BLACK);//标题字体
RtfFont contextFont=new RtfFont("宋体", 12, Font.NORMAL, Color.BLACK);//内容字体
Table table=new Table(3, 11);
//设定没列宽度
int[] widths={20,20,20};
table.setWidths(widths);
table.setWidth(100);//设置表格所在word宽度
table.setAlignment(Element.ALIGN_CENTER);//设置表格字体居中
table.setAutoFillEmptyCells(true);//设置表格自动填满
String titleString="机房维护值班检查表(上班)";
Paragraph title=new Paragraph(titleString, titleFont);
title.setAlignment(Element.ALIGN_CENTER);
doc.add(title);
//设置表头
Cell[] cellHeaders = new Cell[11];
cellHeaders[0] = new Cell(new Phrase("检查区域", contextFont));
cellHeaders[1] = new Cell(new Phrase("具体检查内容", contextFont));
cellHeaders[2] = new Cell(new Phrase("状态确认", contextFont));
for (int i = 0; i < 3; i++) {
cellHeaders[i].setHorizontalAlignment(Element.ALIGN_CENTER);
cellHeaders[i].setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cellHeaders[i]);
}
doc.add(table);
doc.close();
ByteArrayInputStream byteArray=new ByteArrayInputStream(byteArrayOut.toByteArray());
byteArrayOut.close();
return byteArray;
}
[/size][/size]