java 导出csv格式

java 导出csv

本demo地址:https://github.com/woyaochengweidaniu/javaEE/tree/master/file-handling

依赖

  <!-- https://mvnrepository.com/artifact/com.univocity/univocity-parsers -->
        <dependency>
            <groupId>com.univocity</groupId>
            <artifactId>univocity-parsers</artifactId>
            <version>2.8.2</version>
        </dependency>
代码分层使用mybatisplus自动生成

工具类

package com.example.easyexcel.util;

import com.univocity.parsers.csv.CsvWriter;
import com.univocity.parsers.csv.CsvWriterSettings;

import java.io.*;
import java.util.List;

/**
 * @author lcm
 */
public class CsvUtils {

    public static void simpleExport(boolean quoteAllFields, String lineSeparator, String[] heads, List<Object[]> data, String fileName, OutputStream outputStream) throws UnsupportedEncodingException {
        CsvWriterSettings settings = new CsvWriterSettings();
        settings.setQuoteAllFields(quoteAllFields);
        //分割线使用系统默认
        settings.getFormat().setLineSeparator(lineSeparator);
        settings.setIgnoreLeadingWhitespaces(false);
        settings.setIgnoreTrailingWhitespaces(false);
        settings.setHeaders(heads);
        OutputStream csvResult = outputStream;
        //FileOutputStream csvResult =  new FileOutputStream("C:\temp\test.csv");
        //ByteArrayOutputStream csvResult = new ByteArrayOutputStream();

        CsvWriter writer = new CsvWriter(new OutputStreamWriter(csvResult, "UTF-8"), settings);

        writer.writeHeaders();
       writer.writeRows(data);
        writer.close();
        try {
            csvResult.close();
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}


调用, 没有处理业务 直接调用


package com.example.easyexcel.cvs;

 

import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.easyexcel.work.service.IUserService;
import com.example.easyexcel.util.CollectionUtil;
import com.example.easyexcel.util.CsvUtils;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 *
 * 项目源码 :   https://github.com/uniVocity/univocity-parsers
 *
 * maven地址:
 *          <dependency>
 *             <groupId>com.univocity</groupId>
 *             <artifactId>univocity-parsers</artifactId>
 *             <version>2.8.2</version>
 *         </dependency>
 *
 * @author lcm
 */
@RestController
public class CvsController {

    @Autowired
    private IUserService userService;

    /**
     * 导出CVS
     * @param response
     * @throws IOException
     */
    @GetMapping("exportCSV")
    public void exportCVS(HttpServletResponse response) throws IOException {
        ServletOutputStream csvResult = response.getOutputStream();
        response.setContentType("multipart/form-data");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename="+ URLUtil.encode("test", StringUtil.UTF8) +".csv");
        String[] head = new String[]{"用户姓名","年龄","性别","地址","手机号","业余爱好","出生日期","创建时间"};
        List<Map<String, Object>> list = userService.listMaps(new QueryWrapper<>());
        List<Object[]> objects = CollectionUtil.collectToArray(list);
        CsvUtils.simpleExport(true,"
",head,objects,"test",csvResult);
    }

    /**
     * 导入CVS
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping("importCSV")
    public Object uploadCSV(MultipartFile file) throws IOException {
        //##CODE_START

        CsvParserSettings settings = new CsvParserSettings();
        //the file used in the example uses '
' as the line separator sequence.
        //the line separator sequence is defined here to ensure systems such as MacOS and Windows
        //are able to process this file correctly (MacOS uses '
'; and Windows uses '
').
        settings.getFormat().setLineSeparator("
");
        // creates a CSV parser  如果CSV经过Excel打开后文本格式发生改变,导入进来的是乱码
        CsvParser parser = new CsvParser(settings);

        // parses all rows in one go.
        List<String[]> allRows = parser.parseAll(file.getInputStream(),10000);

        for (String[] strings:allRows) {
            System.out.println(Arrays.toString(strings));
        }
        return "success";
    }

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

金枝玉叶9

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值