Java生成Excel表并生成zip包进行下载

生成Excel文件并导出

import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Demo {

	public static void main(String[] args) {
		writeDbtoExcel();
	}
	
	public static String writeDbtoExcel(){
		Connection con = null;
		try {
			// 连接数据库
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:jtds:sqlserver://127.0.0.1:1433/student","sa","admin");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		String path="D:/测试生成Excel表.xls";
		HSSFWorkbook book=new HSSFWorkbook();
		HSSFSheet sheet=book.createSheet("测试");
		String sql="select distinct Student.number,Student.name,Student.phone,Student.status from Student";
		generateExcel(con,sheet,sql);
		
		//用文件输出流类创建名为table的Excel表格
		try {
			FileOutputStream out=new FileOutputStream(path);
			book.write(out);//将HSSFWorkBook中的表写入输出流中
			book.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return path;
	}
	
	public static String generateExcel(Connection con, HSSFSheet sheet, String sql){
		try {
			Statement st=con.createStatement();
			ResultSet rs=st.executeQuery(sql);
			ResultSetMetaData rsmd=rs.getMetaData();//得到结果集的字段名
			int c=rsmd.getColumnCount();//得到数据表的结果集的字段的数量
			//生成表单的第一行,即表头
			HSSFRow row0=sheet.createRow(0);//创建第一行
			for(int i=0;i<c;i++){
				HSSFCell cel=row0.createCell(i);//创建第一行的第i列
				cel.setCellValue(rsmd.getColumnName(i+1));
//				cel.setCellStyle(style);
			}
			//将数据表中的数据按行导入进Excel表中
			int r=1;
			while(rs.next()){
				HSSFRow row=sheet.createRow(r++);//创建非第一行的其他行
				for(int i=0;i<c;i++){//仍然是c列,导入第r行的第i列
					HSSFCell cel=row.createCell(i);
					//以下两种写法均可
//					cel.setCellValue(rs.getString(rsmd.getColumnName(i+1)));
					cel.setCellValue(rs.getString(i+1));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sql;
	}
}

Java将指定文件夹中的内容复制到新的文件夹中

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TestCopy {

	public static void main(String[] args) {
		 
		// 指定文件夹路径
		copy("D:/a", "D:/b");
		System.out.println("共移动文件数目:" + size);
	}
 
	/**
	 * 拷贝文件夹里面所有内容
	 * 
	 * @param sourcePath
	 * @param newPath
	 */
	public static void copy(String sourcePath, String newPath) {
		File file = new File(sourcePath);
		if (file != null && file.exists()) {
			String name = newPath + "/" + sourcePath.substring(sourcePath.lastIndexOf("/") + 1, sourcePath.length());
			// 创建文件夹
			File dir = new File(name);
			if (!dir.exists()) {
				dir.mkdir();
			}
			// 调用拷贝文件的主方法
			copyDir(sourcePath, name);
		} else {
			return;
		}
	}
 
	private static int size;
	/**
	 * 拷贝文件夹
	 * 
	 * @param sourcePath原文件夹
	 * @param newPath指定文件夹
	 */
	private static void copyDir(String sourcePath, String newPath) {
		File sourceFile = new File(sourcePath);
		if (sourceFile.exists() && sourceFile != null) {// 文件存在
			if (sourceFile.isFile()) {
				copyFile(sourcePath, newPath);
				System.out.println(sourcePath + "  --->  " + newPath);
				size++;
			} else if (sourceFile.isDirectory()) {
				// 创建文件夹
				File dir = new File(newPath);
				if (!dir.exists()) {
					dir.mkdir();
				}
				// 获取文件夹内部的文件
				// 递归调用
				for (File con : sourceFile.listFiles()) {
					copyDir(sourcePath + "/" + con.getName(), newPath + "/" + con.getName());
//					System.out.println(sourcePath + "/" + con.getName() + "-----" + newPath + "/" + con.getName());
				}
			}
		} else {
			return;
		}
	}
 
	/**
	 * 拷贝文件
	 * 
	 * @param oldFilePath资源文件
	 * @param newPath指定文件
	 */
	private static void copyFile(String soucePath, String newPath) {
		// 1、确定源
		File sourceFile = new File(soucePath);
		File newFile = new File(newPath);
 
		// 2、确定流
		InputStream fin = null;
		OutputStream fout = null;
 
		try {
			fin = new FileInputStream(sourceFile);
			fout = new FileOutputStream(newFile);
 
			// 3、确定操作
			byte[] flush = new byte[1024];
			int len = -1;
 
			while ((len = fin.read(flush)) != -1) {
				fout.write(flush, 0, len);
			}
 
			// 清空缓冲区
			fout.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 4、关闭流,先打开的后关闭
 
			if (fout != null) {
				try {
					fout.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
 
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

编写zip的工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtilss {
	 private static final int  BUFFER_SIZE = 2 * 1024;
	 /**
	    *  压缩成ZIP 方法1
	  * @param srcDir 压缩文件夹路径 
	  * @param out    压缩文件输出流
	  * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
	  *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
	  * @throws RuntimeException 压缩失败会抛出运行时异常
	  */
	 public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure) throws RuntimeException{
		 long start = System.currentTimeMillis();
		 ZipOutputStream zos = null ;
		 try {
			 zos = new ZipOutputStream(out);
             File sourceFile = new File(srcDir);
             compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
             long end = System.currentTimeMillis();
             System.out.println("压缩完成,耗时:" + (end - start) +" ms");
         } catch (Exception e) {
             throw new RuntimeException("zip error from ZipUtils",e);
         }finally{
             if(zos != null){
                 try {
                     zos.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
     /**
       * 压缩成ZIP 方法2
      * @param srcFiles 需要压缩的文件列表
      * @param out           压缩文件输出流
      * @throws RuntimeException 压缩失败会抛出运行时异常
      */
	public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
         long start = System.currentTimeMillis();
         ZipOutputStream zos = null ;
         try {
             zos = new ZipOutputStream(out);
             for (File srcFile : srcFiles) {
                 byte[] buf = new byte[BUFFER_SIZE];
                 zos.putNextEntry(new ZipEntry(srcFile.getName()));
                 int len;
                 FileInputStream in = new FileInputStream(srcFile);
                 while ((len = in.read(buf)) != -1){
                     zos.write(buf, 0, len);
                 }
                 zos.closeEntry();
                 in.close();
             }
             long end = System.currentTimeMillis();
             System.out.println("压缩完成,耗时:" + (end - start) +" ms");
         } catch (Exception e) {
             throw new RuntimeException("zip error from ZipUtils",e);
         }finally{
             if(zos != null){
                 try {
                     zos.close();
                 } catch (IOException e) {
                     e.printStackTrace();
                 }
             }
         }
     }
	 /**
	      * 递归压缩方法
      * @param sourceFile 源文件
      * @param zos        zip输出流
      * @param name       压缩后的名称
      * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构; 
      *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
      * @throws Exception
      */
	private static void compress(File sourceFile, ZipOutputStream zos, String name, boolean KeepDirStructure) throws Exception{
         byte[] buf = new byte[BUFFER_SIZE];
         if(sourceFile.isFile()){
             // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
             zos.putNextEntry(new ZipEntry(name));
             // copy文件到zip输出流中
             int len;
             FileInputStream in = new FileInputStream(sourceFile);
             while ((len = in.read(buf)) != -1){
                 zos.write(buf, 0, len);
             }
             // Complete the entry
             zos.closeEntry();
             in.close();
         } else {
             File[] listFiles = sourceFile.listFiles();
             if(listFiles == null || listFiles.length == 0){
                 // 需要保留原来的文件结构时,需要对空文件夹进行处理
                 if(KeepDirStructure){
                     // 空文件夹的处理
                     zos.putNextEntry(new ZipEntry(name + "/"));
                     // 没有文件,不需要文件的copy
                     zos.closeEntry();
                 }
             }else {
                 for (File file : listFiles) {
                     // 判断是否需要保留原来的文件结构
                     if (KeepDirStructure) {
                         // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                         // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                         compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                     } else {
                         compress(file, zos, file.getName(),KeepDirStructure);
                     }
                 }
             }
         }
     }
     public static void main(String[] args) throws Exception {
         /** 测试压缩方法1  */
         FileOutputStream fos1 = new FileOutputStream(new File("D:/mytest01.zip"));
         ZipUtilss.toZip("D:/log", fos1,true);
         /** 测试压缩方法2  */
         List<File> fileList = new ArrayList<>();
         fileList.add(new File("D:/tool-java/Java/jdk1.8.0_111/bin/jar.exe"));
         fileList.add(new File("D:/tool-java/Java/jdk1.8.0_111/bin/java.exe"));								// 将文件添加到zip包中
         FileOutputStream fos2 = new FileOutputStream(new File("D:/mytest02 .zip"));
         ZipUtilss.toZip(fileList, fos2);
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章