现在的位置: 首页 > 综合 > 正文

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

2014年06月29日 ⁄ 综合 ⁄ 共 5662字 ⁄ 字号 评论关闭
  1. Java代码    
  2. package com.ljz;  
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.ByteArrayInputStream;  
  6. import java.io.ByteArrayOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.ServletOutputStream;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14. import org.apache.poi.hssf.usermodel.HSSFCell;  
  15. import org.apache.poi.hssf.usermodel.HSSFRow;  
  16. import org.apache.poi.hssf.usermodel.HSSFSheet;  
  17. import org.apache.poi.hssf.usermodel.HSSFWorkbook;  
  18. public class downloadExcelServletextends HttpServlet {  
  19. private static final long serialVersionUID = 1L;  
  20. public downloadExcelServlet() {  
  21. super();  
  22. }  
  23. public void destroy() {  
  24. super.destroy();  
  25. }  
  26. private InputStream getInputStream() {  
  27. HSSFWorkbook wb = new HSSFWorkbook();  
  28. HSSFSheet sheet = wb.createSheet("sheet1");  
  29. HSSFRow row = sheet.createRow(0);  
  30. HSSFCell cell = row.createCell((short0);  
  31. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  32. cell.setCellValue("序号");  
  33. cell = row.createCell((short1);  
  34. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  35. cell.setCellValue("姓");  
  36. cell = row.createCell((short2);  
  37. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  38. cell.setCellValue("名");  
  39. cell = row.createCell((short3);  
  40. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  41. cell.setCellValue("年龄");  
  42. //创建一行记录  
  43. row = sheet.createRow(1);  
  44. cell = row.createCell((short0);  
  45. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  46. cell.setCellValue("1");  
  47. cell = row.createCell((short1);  
  48. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  49. cell.setCellValue("刘");  
  50. cell = row.createCell((short2);  
  51. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  52. cell.setCellValue("继忠");  
  53. cell = row.createCell((short3);  
  54. cell.setEncoding(HSSFCell.ENCODING_UTF_16);  
  55. cell.setCellValue("25");  
  56. // List<User> list = this.findAll();  
  57. //  
  58. // for (int i = 0; i < list.size(); ++i)  
  59. // {  
  60. // User user = 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. ByteArrayOutputStream os = new ByteArrayOutputStream();  
  81. try {  
  82. wb.write(os);  
  83. catch (IOException e) {  
  84. e.printStackTrace();  
  85. }  
  86. byte[] content = os.toByteArray();  
  87. InputStream is = new ByteArrayInputStream(content);  
  88. return is;  
  89. }  
  90. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  91. throws ServletException, IOException {  
  92. response.reset();  
  93. response.setContentType("application/vnd.ms-excel;charset=utf-8");  
  94. response.setHeader("Content-Disposition""attachment;filename="  
  95. new String("系统日志.xls".getBytes(),"iso-8859-1"));  
  96. ServletOutputStream out = response.getOutputStream();  
  97. BufferedInputStream bis = null;  
  98. BufferedOutputStream bos = null;  
  99. try {  
  100. bis = new BufferedInputStream(new
    FileInputStream(file
    );  
  101. bos = new BufferedOutputStream(out);  
  102. byte[] buff = new byte[2048];  
  103. int bytesRead;  
  104. // Simple read/write loop.  
  105. while (-1 != (bytesRead = bis.read(buff,0, buff.length))) {  
  106. bos.write(buff, 0, bytesRead);  
  107. }  
  108. catch (final IOException e) {  
  109. System.out.println("IOException.");  
  110. throw e;  
  111. finally {  
  112. if (bis != null)  
  113. bis.close();  
  114. if (bos != null)  
  115. bos.close();  
  116. }  
  117. }  
  118. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  119. throws ServletException, IOException {  
  120. }  
  121. public void init() throws ServletException {  
  122. // Put your code here  
  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;
	}

【上篇】
【下篇】

抱歉!评论已关闭.