java 实现csv文件导入导出

一.文件导入

  1. 前台页面
<a class="easyui-linkbutton" data-options="iconCls:'icon-undo'"
            onclick="importCsv()">导入a>
function exportCsv() { 
        window.location = ctx+"/system/exportCsv";  
    }
  1. controller代码
/**
     * 导出
     */
    @RequestMapping("exportCsv")
    @ResponseBody
    public void exportCsv(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        List dataList = codeDictManagementService.exportCsv();
        response.setCharacterEncoding("UTF-8");
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
        Date time = new Date();
        String tStamp = format.format(time);
        String filename = "Export" + tStamp + ".csv";
        response.setHeader("contentType", "text/html; charset=UTF-8");
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment; filename=" + filename);
        String cp = request.getSession().getServletContext().getRealPath("/");
        String path = cp + "download/" + filename;
        File file = new File(path);
        /*
         * if (!file.exists() || !file.isDirectory()) { file.mkdir(); }
         */
        BufferedInputStream bis = null;
        BufferedOutputStream out = null;
        FileWriterWithEncoding fwwe = new FileWriterWithEncoding(file, "UTF-8");
        BufferedWriter bw = new BufferedWriter(fwwe);
        if (dataList != null && !dataList.isEmpty())
        {
            for(String data : dataList)
            {
                bw.write(data);
                // 换行
                bw.write("\n");
            }
        }
        bw.close();
        fwwe.close();
        try
        {
            bis = new BufferedInputStream(new FileInputStream(file));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            while(true)
            {
                int bytesRead;
                if (-1 == (bytesRead = bis.read(buff, 0, buff.length)))
                {
                    break;
                }
                out.write(buff, 0, bytesRead);
            }
            file.deleteOnExit();
        }
        catch(IOException e)
        {
            throw e;
        }
        finally
        {
            try
            {
                if (bis != null)
                {
                    bis.close();
                }
                if (out != null)
                {
                    out.flush();
                    out.close();
                }
            }
            catch(IOException e)
            {
                throw e;
            }
        }
        delAllFile(cp + "download/");
    }
  1. service代码
@Override
    public List exportCsv()
    {
        List dataList = new ArrayList();
        try
        {
            List<实体类> list = 获取实体类集合;
            dataList.add("ID,分类项,代码,显示内容,排序值");
            for(int i = 0; i < list.size(); i++)
            {
                dataList.add(list.get(i).getRid() + "," + list.get(i).getCatalogId() + "," + list.get(i).getCode() + "," + list.get(i).getShowValue() + "," + list.get(i).getSortValue());
            }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return dataList;
    }

二.文件导入

  1. 前台代码
<div id="win" class="easyui-dialog" title="上传文件" closed="true"
        style="width: 400px; height:auto;"
        data-options="iconCls:'icon-save',modal:true,collapsible:false,minimizable:false,maximizable:false,buttons:'#bbs',onClose:function(){$('#imgView').attr('src', '');}">
        <form id="importForm" action="" style="padding: 10px 20px 10px 40px;"
             enctype="multipart/form-data" method="post">
            <table>
                <tr>
                <td>上传文件:td>
                tr>
                <tr>
                    <td><input name="file" id="file" type="file" required="required"
                        style="width: 100%" accept=".csv">td>
                tr>
            table>
        form>
    div>
    <div id="bbs">
        <a class="easyui-linkbutton" icon="icon-ok" onClick="submitForm()">保存a>
        <a class="easyui-linkbutton" icon="icon-cancel" onClick="closeWin()">取消a>
    div>
function importCsv() { 
        $("#win").window('open');
    }
    function closeWin() { 
        $("#win").window('close');
    }
    //提交表单数据
        function submitForm() {
               var form = new FormData($('#importForm')[0]);
                $.ajax({
                    url: ctx + '/system/importCsv',
                    type: 'post',
                    data: form,
                    processData:false,
                    contentType:false,
                    success:function(data){
                    $.messager.show({
                            title : '提示',
                            msg : '保存成功',
                            timeout : 3000,
                            showType : 'slide'
                            });
                            refresh(ctx);
                    },
                    error:function(e){
                        showError('保存失败');
                    }
               });
        }

2.controller代码

/**
     * 导入
     */
    @RequestMapping("importCsv")
    @ResponseBody
    public int importCsv(HttpServletRequest request, HttpServletResponse response,MultipartFile file) throws ServletException, IOException
    {
        // 得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
        String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
        savePath = savePath.replace("file:", ""); // 去掉file:
        File file1 = new File(savePath);
        // 判断上传文件的保存目录是否存在
        if (!file1.exists() && !file1.isDirectory())
        {
            file1.mkdir();
        }
        // 删除此路径下的所有文件以及文件夹
        delAllFile(savePath);

        try
        {
            InputStream is = file.getInputStream();// 多文件也适用,我这里就一个文件
            byte[] b = new byte[(int)file.getSize()];
            int read = 0;
            int i = 0;
            while((read = is.read()) != -1)
            {
                b[i] = (byte)read;
                i++;
            }
            is.close();
            String filePath = savePath + "/" + "temp" + "_" + file.getOriginalFilename();
            OutputStream os = new FileOutputStream(new File(savePath + "/" + "temp" + "_" + file.getOriginalFilename()));// 文件原名,如a.txt
            os.write(b);
            os.flush();
            os.close();
            codeDictManagementService.importCsv(filePath);
        }
        catch(Exception e)
        {
            throw e;
        }

        return 1;
    }

3.service代码

@Override
    public int importCsv(String filePath)
    {
        List<String> dataList = CSVUtils.importCsv(new File(filePath));
        if (dataList != null && !dataList.isEmpty())
        {
            for(int i = 1; i < dataList.size(); i++)
            {
                String data = dataList.get(i);
                CodeDict dict = new CodeDict();
                String[] source = data.split(",");
                if (source[0] != "")
                {
                    dict.setRid(source[0]);
                    dict.setCatalogId(source[1]);
                    dict.setCode(source[2]);
                    dict.setShowValue(source[3]);
                    dict.setSortValue(Integer.parseInt(source[4]));
                    codeDictService.addItem(dict);
                }
            }
        }
        return 1;
    }

三.csv文件工具类

package com.southgis.ibase.main.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

public class CSVUtils
{
    /*
     * 导出**
     * 
     * @param file csv文件(路径+文件名),csv文件不存在会自动创建
     * 
     * @param dataList 数据
     * 
     * @return
     */

    public static boolean exportCsv(File file, List dataList)
    {
        boolean isSucess = false;

        FileOutputStream out = null;
        OutputStreamWriter osw = null;
        BufferedWriter bw = null;
        try
        {
            // OutputStreamWriter in_=new OutputStreamWriter(new
            // FileOutputStream("文件名"), "gbk");
            out = new FileOutputStream(file);
            osw = new OutputStreamWriter(out, "UTF-8");
            bw = new BufferedWriter(osw);
            if (dataList != null && !dataList.isEmpty())
            {
                for(String data : dataList)
                {
                    bw.append(data).append("\r");
                }
            }
            isSucess = true;
        }
        catch(Exception e)
        {
            isSucess = false;
        }
        finally
        {
            if (bw != null)
            {
                try
                {
                    bw.close();
                    bw = null;
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (osw != null)
            {
                try
                {
                    osw.close();
                    osw = null;
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (out != null)
            {
                try
                {
                    out.close();
                    out = null;
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        return isSucess;
    }

    /**
     * 导入
     * 
     * @param file
     *          csv文件(路径+文件)
     * @return
     */
    public static List importCsv(File file)
    {
        List dataList = new ArrayList();

        BufferedReader br = null;
        try
        {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(file), "UTF-8");

            br = new BufferedReader(reader);
            String line = "";
            while((line = br.readLine()) != null)
            {
                dataList.add(line);
            }
        }
        catch(Exception e)
        {
        }
        finally
        {
            if (br != null)
            {
                try
                {
                    br.close();
                    br = null;
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                }
            }
        }

        return dataList;
    }

}

四.controller添加文件夹操作代码

// 删除指定文件夹下所有文件
    // param path 文件夹完整绝对路径
    private boolean delAllFile(String path)
    {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists())
        {
            return flag;
        }
        if (!file.isDirectory())
        {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for(int i = 0; i < tempList.length; i++)
        {
            if (path.endsWith(File.separator))
            {
                temp = new File(path + tempList[i]);
            }
            else
            {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile())
            {
                temp.delete();
            }
            if (temp.isDirectory())
            {
                delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);// 再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    // 删除文件夹
    // param folderPath 文件夹完整绝对路径

    private void delFolder(String folderPath)
    {
        try
        {
            delAllFile(folderPath); // 删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            File myFilePath = new File(filePath);
            myFilePath.delete(); // 删除空文件夹
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(文件上传下载,csv,csv工具类,csv文件导入导出)