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);
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章