java生成读取csv_Java Web读取/输出csv文件

本文展示了如何使用Java SpringBoot处理CSV文件。通过一个简单的Demo,讲解了如何从网页上传CSV并解析为数据列表,以及如何生成CSV文件供用户下载。代码中涉及到MultipartFile、HttpServletRequest和HttpServletResponse的使用,以及字符编码的处理,确保中文数据的正确读写。
摘要由CSDN通过智能技术生成

简单实现

1、页面上传csv解析成数组;

2、后台字符串生成csv文件并在页面输出下载。

IDEA新建的SpringBoot Demo project

html页面:

控制器

package com.example.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.RestController;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.*;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

@RestController

@RequestMapping("/file")

public class FileController {

/**

* 导入csv文件

* @param file

* @param request

* @param response

* @throws UnsupportedEncodingException

*/

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)

public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

request.setCharacterEncoding("gb2312");

if (file.isEmpty()) {

System.out.println("文件为空");

return;

}

InputStreamReader isr = null;

BufferedReader br = null;

try {

isr = new InputStreamReader(file.getInputStream(), "gb2312");

br = new BufferedReader(isr);

String line = null;

List> list = new ArrayList<>();

while ((line = br.readLine()) != null) {

list.add(Arrays.asList(line.split(",")));

}

// list即为所得,用于业务操作、数据持久保存等

}

catch (IOException e) {

e.printStackTrace();

}

finally {

try {

if (br != null) {

br.close();

}

if (isr != null) {

isr.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* 导出csv文件

* @param request

* @param response

* @throws IOException

*/

@RequestMapping(value = "/downloadFile", method = RequestMethod.POST)

public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {

response.setContentType("application/x-download");

response.addHeader("Content-Disposition", "attachment;filename="+new String( "导出文件名".getBytes("utf-8"), "ISO8859-1" )+".csv");

OutputStream out = response.getOutputStream();

// 模拟生成字符串,一般是后台查询sql结果集拼接而成

String csvFile = "\"客户姓名\",\"客户类型\",\"联系方式\"\n\"张三\",\"对私\",\"13055874405\t\"\n\"XX集团\",\"对公\",\"0591-8857448\t\"";

// 向out中写入流

out.write((csvFile).toString().getBytes("gb2312"));

out.flush();

response.flushBuffer();

}

}

备注:生成csv文件若要为文本格式需在每个数据后面加\t转义符;

出入参的编码根据实际情况转换(用GB2312编码或可避免中文缺失或乱码问题);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值