java解析CSV文件(zipFiles 打成壓縮包 exportObeEventDataExcel 前端頁面響應)


JAR包及代碼17:39:09

<!-- https://mvnrepository.com/artifact/com.opencsv/opencsv -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>5.2</version>
</dependency>
package mocha.framework.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
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;
import java.io.OutputStreamWriter;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class CSVUtil {
    private static final Logger log  =  Logger.getLogger(CSVUtil.class);
    private static final String filepath = GetProperty.getSfpt("/init.properties", "downloadurl");
    public static File createCSVFile(List<Map<String, Object>> exportData,
            String outPutPath, String filename) {
 
        File csvFile = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            csvFile = new File(outPutPath + filename + ".csv");
            // csvFile.getParentFile().mkdir();
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();
 
            // GB2312使正確讀取分隔符","
            csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "UTF-8"), 1024);
/*            new FileOutputStream(csvFile), "GB2312"), 1024);
*/         // 寫入文件頭部
                     Map<String, Object> map1 = exportData.get(0);
                     if (map1!=null && map1.size()>0) {
                         int num = map1.keySet().size();
                         int j = 0;
                         for (String key : map1.keySet()) {
                             // 第六步,創建單元格,並設置值
                             csvFileOutputStream.write("\""
                                     + key.toString() + "\"");
                             ++j;
                             if (j!=num) {
                                 csvFileOutputStream.write(",");
                             }
                         }
                     }
            csvFileOutputStream.newLine();
            // 寫入文件內容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {  
               // Object row = (Object) iterator.next();  
                LinkedHashMap row = (LinkedHashMap) iterator.next();
                System.out.println(row);
             
                for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {  
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();  
                   // System.out.println( BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
                    csvFileOutputStream.write("\""  
                            +  propertyEntry.getValue().toString() + "\"");  
                   if (propertyIterator.hasNext()) {  
                       csvFileOutputStream.write(",");  
                    }  
               }  
                if (iterator.hasNext()) {  
                   csvFileOutputStream.newLine();  
                }  
           }  
            csvFileOutputStream.flush();  
        } catch (Exception e) {  
           e.printStackTrace();  
        } finally {  
           try {  
                csvFileOutputStream.close();  
            } catch (IOException e) {  
               e.printStackTrace();
           }  
       }  
        return csvFile;
    }
    
    /*************************************************************
                            生成單個CSV文件的方法
    *************************************************************/
    /* 
     * List<Map<String, Object>> Map里面為 表頭 數據 例:Map<"姓名","張三">
     * filename 文件名
     */
    public static String createCSVFileUrl(List<Map<String, Object>> exportData,
            String filename) {
        log.info("開始生成csv文件");
        File csvFile = null;
        String PATH = "";
        FileOutputStream fos = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        BufferedWriter csvFileOutputStream = null;
        try {
            //filepath 文件路徑 :本地就寫   C://Users//A//Downloads//  服務器就寫:/app/file/
            PATH = filepath + filename + ".csv";
            fos = new FileOutputStream(PATH);
            //追加BOM標識 不加會導致office低版本打開亂碼
            fos.write(0xef);
            fos.write(0xbb);
            fos.write(0xbf);
            osw = new OutputStreamWriter(fos, "UTF-8");
            csvFileOutputStream = new BufferedWriter(osw);
            csvFile = new File(PATH);
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();
            log.info(PATH);
            // GB2312使正確讀取分隔符","
            /*csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(csvFile), "UTF-8"), 1024);
            csvFileOutputStream.write(0xef);
            csvFileOutputStream.write(0xbb);
            csvFileOutputStream.write(0xbf);*/
            // 寫入文件頭部
            Map<String, Object> map1 = exportData.get(0);
            if (map1!=null && map1.size()>0) {
                int num = map1.keySet().size();
                int j = 0;
                for (String key : map1.keySet()) {
                    // 第六步,創建單元格,並設置值
                    csvFileOutputStream.write("\""+ key.toString() + "\"");
                    ++j;
                    if (j!=num) {
                        csvFileOutputStream.write(",");
                    }
                }
            }
            csvFileOutputStream.newLine();
//            int i = 0 ;
            // 寫入文件內容
            for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {  
                // Object row = (Object) iterator.next();  
                LinkedHashMap row = (LinkedHashMap) iterator.next();
//                i++;
                //System.out.println(row);
//                if (i%10000 == 0) {
//                    System.out.println("正在寫第"+i+"條數據!");
//                }
                for (Iterator propertyIterator = row.entrySet().iterator(); propertyIterator.hasNext();) {  
                    java.util.Map.Entry propertyEntry = (java.util.Map.Entry) propertyIterator.next();  
                    // System.out.println( BeanUtils.getProperty(row, propertyEntry.getKey().toString()));
                    csvFileOutputStream.write("\""  
                            +  propertyEntry.getValue().toString() + "\"");  
                    if (propertyIterator.hasNext()) {  
                        csvFileOutputStream.write(",");  
                    }  
                }  
                if (iterator.hasNext()) {  
                    csvFileOutputStream.newLine();  
                }  
            }  
            csvFileOutputStream.flush();  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                csvFileOutputStream.close();  
            } catch (IOException e) {  
                e.printStackTrace();
            }  
        }  
        log.info("生成csv文件結束");
        //exportObeEventDataExcel(response,csvFile);
//        List<String> list = new ArrayList<String>();
//        list.add(filepath + filename + ".csv");
//        try {
//            zipFiles(list,filepath+"csv.zip",response);
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
//        if (csvFile.exists() && csvFile.isFile())
//        {
//            csvFile.delete();
//        }
        //返回的是文件的保存地址
        return PATH;
    }
    /*
     * 頁面響應方法
     * */
    public static String exportObeEventDataExcel(HttpServletResponse response,File csvFile){
         try {
                // 以流的形式下載文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(csvFile));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                // 設置response的Header  
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(
                         csvFile.getName(), "UTF-8"));
                response.addHeader("Content-Length", "" + csvFile.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream"); 
                
                //toClient.write(new byte []{(byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
                return "成功";  
            } catch (IOException e) { 
                String message = "export ObeEvent Data Excel failed . ";
                log.error(message, e); 
                return "失敗";
            }
        }
    /*
     * 頁面ZIP響應方法,其實和上面一樣
     */
    public static String exportObeEventDataExcelZip(HttpServletResponse response,File csvFile){
        try {
            // 以流的形式下載文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(csvFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 設置response的Header  
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(
                    csvFile.getName(), "UTF-8"));
            response.addHeader("Content-Length", "" + csvFile.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream"); 
            //toClient.write(new byte []{(byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            return "成功";  
        } catch (IOException e) { 
            String message = "export ObeEvent Data Excel failed . ";
            log.error(message, e); 
            return "失敗";
        }
    }
    
    /**
     * @param fileRealPathList 待壓縮的文件列表
     * @param zipFileRealPath  壓縮后的文件名稱
     * @return boolean
     * @throws :Exception
     * @Function: zipFiles
     * @Description:多個文件的ZIP壓縮
     */
    public static void zipFiles(List<String> fileRealPathList, String zipFileRealPath,
            HttpServletResponse response)
        throws IOException
    {
        FileOutputStream out = null;
        ZipOutputStream zipOut = null;
        String path = filepath+zipFileRealPath+".zip";
        try
        {
            // 根據文件路徑構造一個文件實例
            File zipFile = new File(path);
            // 判斷目前文件是否存在,如果不存在,則新建一個
            if (!zipFile.exists())
            {
                zipFile.createNewFile();
            }
            // 根據文件路徑構造一個文件輸出流
            out = new FileOutputStream(path);
            // 傳入文件輸出流對象,創建ZIP數據輸出流對象
            zipOut = new ZipOutputStream(out);
            // 循環待壓縮的文件列表
            for (String fileRealPath : fileRealPathList)
            {
                FileInputStream in = null;
                try
                {
                    File file = new File(fileRealPath);
                    if (!file.exists())
                    {
                        log.error("文件不存在");
                        throw new FileNotFoundException("文件不存在");
                    }
 
                    // 創建文件輸入流對象
                    in = new FileInputStream(fileRealPath);
                    // 得到當前文件的文件名稱
                    //判斷操作系統
                    String separateCharacter = "";
                    String os = System.getProperty("os.name");
                    if (os.toLowerCase().startsWith("win"))
                    {
                        //windows操作系統
                        separateCharacter = "//";
                    }
                    else
                    {
                        //非windows操作系統
                        separateCharacter = "/";
                    }
                    String fileName = fileRealPath.substring(
                        fileRealPath.lastIndexOf(separateCharacter) + 1, fileRealPath.length());
                    // 創建指向壓縮原始文件的入口
                    ZipEntry entry = new ZipEntry(fileName);
                    zipOut.putNextEntry(entry);
                    // 向壓縮文件中輸出數據
                    int nNumber = 0;
                    byte[] buffer = new byte[512];
                    while ((nNumber = in.read(buffer)) != -1)
                    {
                        zipOut.write(buffer, 0, nNumber);
                    }
                }
                catch (IOException e)
                {
                    log.error("文件壓縮異常-in,原因:", e);
                    throw new IOException("文件壓縮異常");
                }
                finally
                {
                    // 關閉創建的流對象
                    if (null != in)
                    {
                        in.close();
                    }
                }
            }
        }
        catch (IOException e)
        {
            log.error("文件壓縮異常-out,原因:", e);
            throw new IOException("文件壓縮異常");
        }
        finally
        {
            if (null != zipOut)
            {
                zipOut.close();
            }
            if (null != out)
            {
                out.close();
            }
        }
        File fiel = new File(path);
        //調用導出到前端的方法
        exportObeEventDataExcelZip(response,fiel);
        //刪除本地壓縮包
        if (fiel.exists() && fiel.isFile())
        {
            fiel.delete();
        }
        //刪除其他文件
        for (String string : fileRealPathList) {
             File fiel1 = new File(string);
             //刪除本地壓縮包
             if (fiel1.exists() && fiel1.isFile())
             {
                 fiel1.delete();
             }
        }
    }
    public static void main(String[] args) {
        List exportData = new ArrayList<Map>();
        Map row1 = new LinkedHashMap<String, String>();
        row1.put("11", "11");
        row1.put("21", "12");
        row1.put("31", "13");
        row1.put("41", "14");
        exportData.add(row1);
        row1 = new LinkedHashMap<String, String>();
        row1.put("11", "21");
        row1.put("2", "22");
        row1.put("31", "23");
        row1.put("4", "24");
        exportData.add(row1);
        List propertyNames = new ArrayList();
        CSVUtil.createCSVFile(exportData, "C:\\Users\\A\\Downloads\\", "導出CSV文件");
    }
}
View Code


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM