最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java?導出?CSV?文件操作詳情

 更新時間:2022年08月17日 15:33:25   作者:苦糖????????  
這篇文章主要介紹了Java導出CSV文件操作詳情,文章通過導入坐標展開詳細內容介紹,具有一定的參考價值,需要的小伙伴可以參考一下

首先第一步 導入坐標:

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.6</version>
</dependency>

第二步

引入工具類 說明下 因為這個工具類用到是Listj集合
我就順帶吧 實體類和map 之間的轉換也說了

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
* 導出至csv文件
* */
public class CsvUtil {
//CSV文件分隔符
private final static String NEW_LINE_SEPARATOR="\n";
/** CSV文件列分隔符 */
private static final String CSV_COLUMN_SEPARATOR = ",";
/** CSV文件列分隔符 */
private static final String CSV_RN = "\r\n";

/**寫入csv文件
* @param headers 列頭
* @param data 數(shù)據(jù)內容
* @param filePath 創(chuàng)建的csv文件路徑
* @throws IOException **/
public static void writeCsvWithHeader(String[] headers, List<Object[]> data, String filePath) {
//初始化csvformat
CSVFormat format = CSVFormat.DEFAULT.withHeader(headers);
try {
//根據(jù)路徑創(chuàng)建文件,并設置編碼格式
FileOutputStream fos = new FileOutputStream(filePath);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
//創(chuàng)建CSVPrinter對象
CSVPrinter printer = new CSVPrinter(osw, format);

if(null!=data){
//循環(huán)寫入數(shù)據(jù)
for(Object[] lineData:data){
printer.printRecord(lineData);
}
}
printer.flush();
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**寫入csv文件
* @param headers 列頭
* @param data 數(shù)據(jù)內容
* @param filePath 創(chuàng)建的csv文件路徑
* @throws IOException **/
public static void writeCsvWithRecordSeparator(Object[] headers, List<Object[]> data, String filePath){
//初始化csvformat
CSVFormat format = CSVFormat.DEFAULT.withRecordSeparator(NEW_LINE_SEPARATOR);
try {
//根據(jù)路徑創(chuàng)建文件,并設置編碼格式
FileOutputStream fos = new FileOutputStream(filePath);
OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
//創(chuàng)建CSVPrinter對象
CSVPrinter printer = new CSVPrinter(osw,format);
//寫入列頭數(shù)據(jù)
printer.printRecord(headers);

if(null!=data){
//循環(huán)寫入數(shù)據(jù)
for(Object[] lineData:data){
printer.printRecord(lineData);
}
}
printer.flush();
printer.close();
System.out.println("CSV文件創(chuàng)建成功,文件路徑:"+filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @filePath 文件路徑
*/
public static List<CSVRecord> readCsvParse(String filePath){
List<CSVRecord> records = new ArrayList<>();
try {
FileInputStream in = new FileInputStream(filePath);
BufferedReader reader = new BufferedReader (new InputStreamReader(in,"GBK"));
CSVParser parser = CSVFormat.EXCEL.parse(reader);
records = parser.getRecords();
parser.close();
} catch (IOException e) {
e.printStackTrace();
}finally {
return records;
}
}

/**
* 自定義字段
* @filePath 文件路徑
*/
public static List<CSVRecord> readCsvParseWithHeader(String filePath,String[] headers){
List<CSVRecord> records = new ArrayList<>();
try {
FileInputStream in = new FileInputStream(filePath);
BufferedReader reader = new BufferedReader (new InputStreamReader(in,"GBK"));
CSVParser parser = CSVFormat.EXCEL.withHeader(headers).parse(reader);
records = parser.getRecords();
/*for (CSVRecord record : parser.getRecords()) {
System.out.println(record.get("id") + ","
+ record.get("name") + ","
+ record.get("code"));
}*/
parser.close();
}catch (IOException e){
e.printStackTrace();
}finally {
return records;
}
}
/**
* 導出至多個csv文件
* */
public void writeMuti() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
CountDownLatch doneSignal = new CountDownLatch(2);

List<Map<String, String>> recordList = new ArrayList<>();

executorService.submit(new CsvExportThread("E:/0.csv", recordList, doneSignal));
executorService.submit(new CsvExportThread("E:/1.csv", recordList, doneSignal));

doneSignal.await();
System.out.println("Finish!!!");
}
/**
* @param colNames 表頭部數(shù)據(jù)
* @param dataList 集合數(shù)據(jù)
* @param mapKeys 查找的對應數(shù)據(jù)
*/
public static ByteArrayOutputStream doExport(String[] colNames, String[] mapKeys, List<Map> dataList) {
try {
StringBuffer buf = new StringBuffer();

// 完成數(shù)據(jù)csv文件的封裝
// 輸出列頭
for (int i = 0; i < colNames.length; i++) {
buf.append(colNames[i]).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);

if (null != dataList) { // 輸出數(shù)據(jù)
for (int i = 0; i < dataList.size(); i++) {
for (int j = 0; j < mapKeys.length; j++) {
buf.append(dataList.get(i).get(mapKeys[j])).append(CSV_COLUMN_SEPARATOR);
}
buf.append(CSV_RN);
}
}
// 寫出響應
ByteArrayOutputStream os = new ByteArrayOutputStream();
//OutputStream os = new ByteArrayOutputStream();
os.write(buf.toString().getBytes("GBK"));
os.flush();
os.close();
return os;
} catch (Exception e) {
LogUtils.error("doExport錯誤...", e);
e.printStackTrace();
}
return null;
}
public static HttpHeaders setCsvHeader(String fileName) {
HttpHeaders headers = new HttpHeaders();
try {
// 設置文件后綴
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filename = new String(fileName.getBytes("gbk"), "iso8859-1") + sdf.format(new Date()) + ".csv";
headers.add("Pragma", "public");
headers.add("Cache-Control", "max-age=30");
headers.add("Content-Disposition", "attachment;filename="+filename);
headers.setContentType(MediaType.valueOf("application/vnd.ms-excel;charset=UTF-8"));
}catch (Exception e){
e.printStackTrace();
}
return headers;
}
}

第三步

controller 層:

package com.example.demo.controller;

import com.example.demo.service.DemoService;
import com.example.demo.util.CsvUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/demo")
public class DemoController {

@Autowired
private DemoService demoService;

@RequestMapping("/exportCsv")
public ResponseEntity<byte[]> exportCsv(){
//設置excel文件名
String fileName="用戶表";
//設置HttpHeaders,設置fileName編碼,排除導出文檔名稱亂碼問題
HttpHeaders headers = CsvUtil.setCsvHeader(fileName);
byte[] value = null;
try {
//獲取要導出的數(shù)據(jù)
value = this.demoService.exportCsv();
}catch (Exception e){
e.printStackTrace();
}
return new ResponseEntity<byte[]>(value,headers, HttpStatus.OK);
}
}

第四步:

service 接口

package com.example.demo.service;

public interface DemoService {
/*導出csv文件*/
byte[] exportCsv();
}

第五步:

service 實現(xiàn)類

package com.example.demo.service.impl;
import com.example.demo.pojo.User;
import com.example.demo.service.DemoService;
import com.example.demo.util.CsvUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DemoServiceImpl implements DemoService {

@Override
public byte[] exportCsv() {
byte[] content = null;
try {
String[] sTitles = new String[]{"名稱","年齡","性別"};
String[] mapKeys = new String[]{"name","age","sex"};
List<Map> dataList = new ArrayList<>();
//數(shù)據(jù)
for (int i = 0; i < 10; i++) {
User user = new User("小明" + i, i, "男" + i);
Map map = BeanUtils.describe(user);
dataList.add(map);
}

ByteArrayOutputStream os = CsvUtil.doExport(sTitles,mapKeys,dataList);
content = os.toByteArray();
}catch (Exception e){
e.printStackTrace();
}
return content;
}
}

補充 :

象和map 互相轉換
坐標

<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>

用到的工具類:

BeanUtils

1. bean(?? ?實體類???)轉Map

例子:

Person person=new Person();
person1.setName("張三");
person1.setSex("不男不女");
Map<String, Object> map=null;

map = BeanUtils.describe(person1);

2. map轉bean(實體類)

例子: 估計誰沒事也不會用map 轉bean 可能是我見識短了/**

* Map轉換層Bean,使用泛型免去了類型轉換的麻煩。
* @param <T>
* @param map
* @param class1
* @return
*/
public static <T> T map2Bean(Map<String, String> map, Class<T> class1) {
T bean = null;
try {
bean = class1.newInstance();
BeanUtils.populate(bean, map);
} catch (Exception e) {
e.printStackTrace();
}
return bean;
}

到此這篇關于Java 導出 CSV 文件操作詳情的文章就介紹到這了,更多相關Java 導出 CSV 文件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論

昭通市| 巴楚县| 乌什县| 玉树县| 黄浦区| 新安县| 简阳市| 灵宝市| 且末县| 巧家县| 泸溪县| 遂昌县| 富川| 璧山县| 汨罗市| 罗甸县| 武夷山市| 丹阳市| 广河县| 会同县| 二连浩特市| 夹江县| 普陀区| 牟定县| 柳林县| 浦县| 定西市| 黎平县| 曲阳县| 惠来县| 肃南| 绥阳县| 宁蒗| 大庆市| 黎平县| 黄骅市| 新昌县| 衡南县| 会理县| 洛川县| 遂昌县|