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,"\n",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 '\n' 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 '\r'; and Windows uses '\r\n').
        settings.getFormat().setLineSeparator("\n");
        // 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";
    }



}


免責聲明!

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



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