springboot查数据并以csv格式现在到本地

csv工具类:

package cn.com.rivercloud.util;

import com.csvreader.CsvWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.Collection;
import java.util.Iterator;

/**
 * CSV工具类
 * @author shichangle
 * date 2020/1/15 0015 15:19
 */
public class CSVUtil {

    private static final Logger logger = LoggerFactory.getLogger(CSVUtil.class);

    /**
     *
     * @param list 具体数据
     * @param csvFilePath 文件路径
     * @param csvHeaders 表头
     * @param <T>
     */
    public static <T> void writeCSV(Collection<T> list,String csvFilePath,String[] csvHeaders){
        try {
            //定义路径、分隔符、编码  注意分隔符英文与中文的区别
            CsvWriter csvWriter = new CsvWriter(csvFilePath, ',', Charset.forName("UTF-8"));

            //写表头
            csvWriter.writeRecord(csvHeaders);

            //写内容
            Iterator<T> iterator = list.iterator();

            while(iterator.hasNext()){
                T next = (T)iterator.next();
                //获取类属性
                Field[] fields = next.getClass().getDeclaredFields();
                String[] csvContent = new String[fields.length];
                for (int i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    String name = field.getName();
                    String getMethodName = "get" +name.substring(0,1).toUpperCase()+name.substring(1);

                    try {
                        Class clazz= next.getClass();
                        Method method = clazz.getMethod(getMethodName, new Class[]{});
                        Object value = method.invoke(next, new Object[]{});
                        if(value==null){
                            continue;
                        }
                        //取值并赋值给数组
                        String textValue = value.toString();
                        csvContent[i] = textValue;
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (SecurityException e) {
                        e.printStackTrace();
                    }
                }
                csvWriter.writeRecord(csvContent);
            }
            csvWriter.close();
            logger.info("csv文件写入成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

FileUtil工具类:

package cn.com.rivercloud.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * author shichangle
 * date 2020/1/2 0002 11:37
 */
public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);


    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    public static String fileToString(File readFile) {
        String str = "";
        try {
            FileInputStream in = new FileInputStream(readFile);
            // size 为字串的长度 ,这里一次性读完
            int size = in.available();
            byte[] buffer = new byte[size];
            in.read(buffer);
            in.close();
            str = new String(buffer);
        } catch (IOException e) {
            return null;
        }
        return str;
    }

    /**
     * @param filePath
     * @param fileName
     * @return
     */
    public static boolean downloadFile(HttpServletResponse response,String filePath, String fileName) {

        if (fileName != null) {
            File file = new File(filePath, fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.setHeader("content-type","application/octet-stream");
                response.setHeader("Content-Disposition","attachment;fileName="+fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis =  null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream outputStream = response.getOutputStream();
                    int i = 0;
                    while((i=bis.read(buffer))!=-1){
                        outputStream.write(buffer,0,i);
                        System.out.println(bis.available());
              //这里需要flush一下,否则我的文件值输出一部分 outputStream.flush(); }
            //我在这里将这个流关闭,否则返回页面的参数也会写到这个文件中去 outputStream.close(); logger.info(
"下载文件成功"); return true; } catch (Exception e) { e.printStackTrace(); logger.error("下载文件失败:"+e); return false; }finally { if(bis!=null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } if(bis!=null){ try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } return false; } }

具体service:

@Override
    public boolean exportLog(Query query, HttpServletResponse response) {
        try {
            //查询数据库数据
            List<SysLogs> list = getSysLogsList(query);
            //文件表头
            String[] csvHeaders = {"handleTime", "username", "requestIp", "handlePage", "result"};

            //设置服务器存储文件的路径
            String savePath = ResourceUtils.getURL("csmsystem/src/main/resources/log").getPath();
            File file = new File(savePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE,-1);
            Date time = calendar.getTime();
            String date = new SimpleDateFormat("yyyyMMdd_HHmm").format(time);

            String filename = date+"sysLog.csv";
            String localFileName = file + "/" + filename;

            //存储到服务器
            CSVUtil.writeCSV(list, localFileName, csvHeaders);
            //下载到本地
            boolean b = FileUtil.downloadFile(response, savePath, filename);
            if(b){
                return true;
            }else {
                logger.error("下载文件出错");
                return false;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        }
    }
原文地址:https://www.cnblogs.com/notchangeworld/p/12199686.html