POI生成Excel并通过Servlet下载示例

本文提供了一个使用Java实现的简单示例,展示如何通过Apache POI库创建并下载包含表格数据的Excel文件。该示例包括了创建表格、填充数据、设置字符编码以及将Excel文件返回给客户端的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Java代码
  2. packagecom.ljz;
  3. importjava.io.BufferedInputStream;
  4. importjava.io.BufferedOutputStream;
  5. importjava.io.ByteArrayInputStream;
  6. importjava.io.ByteArrayOutputStream;
  7. importjava.io.IOException;
  8. importjava.io.InputStream;
  9. importjavax.servlet.ServletException;
  10. importjavax.servlet.ServletOutputStream;
  11. importjavax.servlet.http.HttpServlet;
  12. importjavax.servlet.http.HttpServletRequest;
  13. importjavax.servlet.http.HttpServletResponse;
  14. importorg.apache.poi.hssf.usermodel.HSSFCell;
  15. importorg.apache.poi.hssf.usermodel.HSSFRow;
  16. importorg.apache.poi.hssf.usermodel.HSSFSheet;
  17. importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
  18. publicclassdownloadExcelServletextendsHttpServlet{
  19. privatestaticfinallongserialVersionUID=1L;
  20. publicdownloadExcelServlet(){
  21. super();
  22. }
  23. publicvoiddestroy(){
  24. super.destroy();
  25. }
  26. privateInputStreamgetInputStream(){
  27. HSSFWorkbookwb=newHSSFWorkbook();
  28. HSSFSheetsheet=wb.createSheet("sheet1");
  29. HSSFRowrow=sheet.createRow(0);
  30. HSSFCellcell=row.createCell((short)0);
  31. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  32. cell.setCellValue("序号");
  33. cell=row.createCell((short)1);
  34. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  35. cell.setCellValue("姓");
  36. cell=row.createCell((short)2);
  37. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  38. cell.setCellValue("名");
  39. cell=row.createCell((short)3);
  40. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  41. cell.setCellValue("年龄");
  42. //创建一行记录
  43. row=sheet.createRow(1);
  44. cell=row.createCell((short)0);
  45. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  46. cell.setCellValue("1");
  47. cell=row.createCell((short)1);
  48. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  49. cell.setCellValue("刘");
  50. cell=row.createCell((short)2);
  51. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  52. cell.setCellValue("继忠");
  53. cell=row.createCell((short)3);
  54. cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  55. cell.setCellValue("25");
  56. //List<User>list=this.findAll();
  57. //
  58. //for(inti=0;i<list.size();++i)
  59. //{
  60. //Useruser=list.get(i);
  61. //
  62. //row=sheet.createRow(i+1);
  63. //
  64. //cell=row.createCell((short)0);
  65. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  66. //cell.setCellValue(i+1);
  67. //
  68. //cell=row.createCell((short)1);
  69. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  70. //cell.setCellValue(user.getFirstname());
  71. //
  72. //cell=row.createCell((short)2);
  73. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  74. //cell.setCellValue(user.getLastname());
  75. //
  76. //cell=row.createCell((short)3);
  77. //cell.setEncoding(HSSFCell.ENCODING_UTF_16);
  78. //cell.setCellValue(user.getAge());
  79. //}
  80. ByteArrayOutputStreamos=newByteArrayOutputStream();
  81. try{
  82. wb.write(os);
  83. }catch(IOExceptione){
  84. e.printStackTrace();
  85. }
  86. byte[]content=os.toByteArray();
  87. InputStreamis=newByteArrayInputStream(content);
  88. returnis;
  89. }
  90. publicvoiddoGet(HttpServletRequestrequest,HttpServletResponseresponse)
  91. throwsServletException,IOException{
  92. response.reset();
  93. response.setContentType("application/vnd.ms-excel;charset=utf-8");
  94. response.setHeader("Content-Disposition","attachment;filename="
  95. +newString("系统日志.xls".getBytes(),"iso-8859-1"));
  96. ServletOutputStreamout=response.getOutputStream();
  97. BufferedInputStreambis=null;
  98. BufferedOutputStreambos=null;
  99. try{
  100. bis=newBufferedInputStream(new FileInputStream(file);
  101. bos=newBufferedOutputStream(out);
  102. byte[]buff=newbyte[2048];
  103. intbytesRead;
  104. //Simpleread/writeloop.
  105. while(-1!=(bytesRead=bis.read(buff,0,buff.length))){
  106. bos.write(buff,0,bytesRead);
  107. }
  108. }catch(finalIOExceptione){
  109. System.out.println("IOException.");
  110. throwe;
  111. }finally{
  112. if(bis!=null)
  113. bis.close();
  114. if(bos!=null)
  115. bos.close();
  116. }
  117. }
  118. publicvoiddoPost(HttpServletRequestrequest,HttpServletResponseresponse)
  119. throwsServletException,IOException{
  120. }
  121. publicvoidinit()throwsServletException{
  122. //Putyourcodehere
  123. }
  124. }



public class UploadAction{
	private TPoiService ts;
	
	public TPoiService getTs() {
		return ts;
	}

	public void setTs(TPoiService ts) {
		this.ts = ts;
	}

	public File getNewFile(String path){
		File file=new File(path);
		File[] dir=file.listFiles();
		System.out.println(dir.length);
		int[] newfiles=new int[dir.length];
		for (int i = 0; i < dir.length; i++) {
//			System.out.println(dir[i]);
			newfiles[i]=Integer.parseInt(dir[i].getName().substring(0,dir[i].getName().indexOf(".")));
		}
		int num1=newfiles[0];
		for (int j = 0; j < newfiles.length; j++) {
			if(newfiles[j]>num1){
				num1=newfiles[j];
			}
		}
		System.out.println(num1);
		return new File(path+"\\"+num1+".xls");
	}
	
	@Action(value="upload",className="upload",results={@Result(name="success",location="/upload.jsp",type="dispatcher"),
			@Result(name="error",location="/Page/error.jsp",type="dispatcher")})
	public String upload() throws IOException{
		System.out.println("this is upload");
		HttpServletResponse response=ServletActionContext.getResponse();
//		PrintWriter out = response.getWriter();
		File file=getNewFile(ServletActionContext.getRequest().getRealPath("xls"));
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");

		response.setHeader("Content-Disposition", "attachment;filename="+ new String("isd.xls".getBytes(), "iso-8859-1"));
		
		ServletOutputStream out = response.getOutputStream();  
		 
		BufferedInputStream bis = null;
		 
		BufferedOutputStream bos = null;
		 
		try {  
		    bis = new BufferedInputStream(new FileInputStream(file) {
		    @Override
		    public int read() throws IOException {
		      // TODO Auto-generated method stub
		        return 0;
		    }
		 });  
		     bos = new BufferedOutputStream(out);  
		 
		     byte[] buff = new byte[2048];  
		 
		     int bytesRead;  
		 
		     // Simple read/write loop.  
		     while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
		            bos.write(buff, 0, bytesRead);  
		        }
		    } catch (final IOException e) {  
		        System.out.println("IOException.");  
		        throw e;  
		    } finally {  
		        if (bis != null)  
		            bis.close();  
		        if (bos != null)  
		            bos.close();  
		    }  
		return null;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值