- 首页 > it技术 > >
CSV|SpringBoot JAVA导出数据到CSV文件
1.CSV工具类
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 数据内容
* @param filePath 创建的csv文件路径
* @throws IOException **/
public static void writeCsvWithHeader(String[] headers, List
2.定义接口
public interface DemoService {
/*导出csv文件*/
byte[] exportCsv();
}
3.接口实现类
@Service
public class DemoServiceImpl implements DemoService {
@Autowired
private SysToolsMapper toolsMapper;
@Override
public byte[] exportCsv() {
byte[] content = null;
try {
String[] sTitles = new String[]{"名称","链接","图标"};
String[] mapKeys = new String[]{"toolName","toolLink","toolIcon"};
List
4.springboot调用接口
@Controller
@RequestMapping("/demo")
public class DemoController {@Autowired
private DemoService demoService;
@RequestMapping("/exportCsv")
public ResponseEntity exportCsv(){
//设置excel文件名
String fileName="信息报表";
//设置HttpHeaders,设置fileName编码,排除导出文档名称乱码问题
HttpHeaders headers = CsvUtil.setCsvHeader(fileName);
byte[] value = https://www.it610.com/article/null;
try {
//获取要导出的数据
value = this.demoService.exportCsv();
}catch (Exception e){
e.printStackTrace();
}
return new ResponseEntity(value,headers, HttpStatus.OK);
}
}
【CSV|SpringBoot JAVA导出数据到CSV文件】4.maven引入jar包
org.apache.commons
commons-csv
1.6
推荐阅读