zoukankan      html  css  js  c++  java
  • 下载zip格式文件(压缩Excel文件为zip格式)

    Mongodb配置文件参考这一篇:http://www.cnblogs.com/byteworld/p/5913061.html

    package util;
    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import org.apache.commons.compress.archivers.zip.Zip64Mode;
    import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
    import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.Row;
    import org.apache.poi.ss.usermodel.Sheet;
    import org.apache.poi.ss.usermodel.Workbook;
    import com.mongodb.DBCollection;
    import com.mongodb.DBCursor;
    import com.mongodb.DBObject;
    import com.sun.corba.se.spi.orbutil.fsm.Input;
    
    public class CreateExcel {  
        /**
         * 把文件压缩到zip中
         * @Description:
         * @param   
         * @return void 返回类型
         */
        public static void createZip(String dir,OutputStream out){
            // 用户目录下的文件
            File[] f = new File("E:/"+dir).listFiles();
            // 创建zip文件
            ZipArchiveOutputStream zipOut = null;
            InputStream input = null;
            try {
                zipOut = new ZipArchiveOutputStream(out);
                zipOut.setEncoding("UTF-8");
                zipOut.setUseZip64(Zip64Mode.AsNeeded);
                // 遍历目录下的文件
                for(File file:f){
                    if (file != null) {
                        ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, file.getName());
                        zipOut.putArchiveEntry(zipEntry);
                        // 读取文件
                        input = new BufferedInputStream(new FileInputStream(file));
                        byte[] buff = new byte[1024];
                        int len = 0;
                        while((len = input.read(buff)) != -1){
                            zipOut.write(buff, 0, len);
                        }
                        zipOut.closeArchiveEntry();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally{
                if (input != null) {
                    try {
                        input.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (zipOut != null) {
                    try {
                        zipOut.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        
       
        
        /**
         * 创建Excel文件到本地
         * @Description:
         * @param   
         * @return void 返回类型
         */
        public static void createExcel(String userid,String file,DBCursor cursor){
            // 根据用户名创建文件夹
            File dir = new File("E:/" + userid);
            if (!dir.isDirectory()) {
                dir.mkdirs();
            }
            Workbook book = new HSSFWorkbook();
            // 获取标题
            DBObject ob = cursor.toArray().get(0);
            ArrayList<String> title = new ArrayList<>();
            for(String key:ob.keySet()){
                if (key.equals("_id")) {
                    continue;
                }
                title.add(key);
            }
            // 创建sheet
            Sheet sheet = book.createSheet();
            OutputStream out = null;
            try {
                // 写入标题栏
                Row row = null;
                // 标题栏的行数
                Cell cell = null;
                for(int i = 0;i< (cursor.count() + 1);i++){
                    // 标题栏
                    if (i == 0) {
                        row = sheet.createRow(i);
                        for (int j = 0; j < title.size(); j++) {
                            cell = row.createCell(j);
                            // 设置标题栏
                            cell.setCellValue(title.get(j));
                        }
                        continue;
                    }
                    // 写入数据
                    row = sheet.createRow(i);
                    out = new FileOutputStream(dir+"/"+file);
                    DBObject obj = null;
                    for (int j = 0; j < title.size(); j++) {
                        cell = row.createCell(j);
                        obj = cursor.toArray().get(j);    
                        for(String key :obj.keySet()){
                            if (key.equals("_id")) {
                                continue;
                            }
                            if (key.equals(title.get(j))) {
                                cell.setCellValue((String)(obj.get(key)));
                            }
                        }
                    }
                }
                // 写入到excel
                book.write(out);
            } catch (IOException e1) {
                e1.printStackTrace();
            } finally {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    

      JSP:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
            <form method="post">
                <a href="/Demo/SimpleDown"><h2>下载</h2></a>
            </form>
    </body>
    </html>
    

      Servlet:

    package servlet;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.zip.ZipOutputStream;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.compress.archivers.zip.Zip64Mode;
    import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
    import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
    import com.mongodb.DBCollection;
    
    import util.CreateExcel;
    import util.DBConn;
    
    /**
     * 单独文件的zip下载
     */
    @WebServlet("/SimpleDown")
    public class SimpleDown extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public SimpleDown() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doPost(request, response);
    	}
    	
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		//DBCollection conn = DBConn.getConn();
    	    DBCollection conn = DBConn.getConn();
    	    CreateExcel.createExcel("User2323","weixin_data.xls", conn.find());
    	      //createZip("User2323");
    	   // CreateExcel.delZip("User2323"); 
    	    response.setCharacterEncoding("UTF-8");
    	    response.setHeader("Content-Disposition", "attachment;filename="+"User2323.zip");
    	    CreateExcel.createZip("User2323", response.getOutputStream());
    	
    	}
    	
    	
    	 
     
    	
    }
    

      

  • 相关阅读:
    LeetCode 275. H-Index II
    LeetCode 274. H-Index
    LeetCode Gray Code
    LeetCode 260. Single Number III
    LeetCode Word Pattern
    LeetCode Nim Game
    LeetCode 128. Longest Consecutive Sequence
    LeetCode 208. Implement Trie (Prefix Tree)
    LeetCode 130. Surrounded Regions
    LeetCode 200. Number of Islands
  • 原文地址:https://www.cnblogs.com/byteworld/p/5919094.html
Copyright © 2011-2022 走看看