multipartfile转excel_java实现CSV⽂件导⼊与导出功能年前在开发功能模块的时候⽤到了CSV⽂件导⼊导出,就此整理⼀下,便于⼤家参考。
导⼊导出功能很多时候⽤到的都是excel⽂件,但是现在越来越多的使⽤了CSV⽂件进⾏此操作,它是⼀个纯⽂本⽂件,可以⽤记事本打开,也可以⽤Excel打开。CSV⽂件不像Excel那样有很多条条框框,它使⽤硬回车分割每条记录,⽤逗号分隔每条数据的字段。
CSV格式的⽂件就是⽤硬回车和⽂本都好实现的表格,⽤Excel⼀读就成了表格。⽂件名后缀就是 .csv。
直接上代码吧!
导⼊部分
导⼊的时候基于Ajax请求,js代码如下: function importIpMac(upload) {
var importTextInfo = ElementById("importTextInfo");
importTextInfo.value="";
$.ajaxFileUpload({
url: ctx + "/ipmac/importIpMac",
type: 'post',
secureuri: false, // ⼀般设置为false
fileElementId: 'upload', // 上传⽂件的id、name属性名
dataType: 'text', // 返回值类型,⼀般设置为json、application/json
success: function(data, status){
getIpMacBase();
},
error: function(data, status, e){
alert('请求异常!');
}
});
}
java代码控制层: /**
* 导⼊
getsavefilename*/
@ResponseBody
@RequestMapping(value = "/importIpMac", method = RequestMethod.POST, headers = { "content-type=multipart/form-data" })
public int importIpMac(HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "upload") MultipartFile[] buildInfo)
throws ServletException, IOException {
// 得到上传⽂件的保存⽬录,将上传的⽂件存放于WEB-INF⽬录下,不允许外界直接访问,保证上传⽂件的安全
String savePath = Session().getServletContext().getRealPath("/WEB-INF/upload");
savePath = place("file:", ""); // 去掉file:
File file1 = new File(savePath);
// 判断上传⽂件的保存⽬录是否存在
if (!ists() && !file1.isDirectory()) {
log.info(savePath + "⽬录不存在,需要创建");
file1.mkdir();
}
// 删除此路径下的所有⽂件以及⽂件夹
delAllFile(savePath);
try {
InputStream is = buildInfo[0].getInputStream();// 多⽂件也适⽤,我这⾥就⼀个⽂件
byte[] b = new byte[(int) buildInfo[0].getSize()];
int read = 0;
int i = 0;
while ((read = is.read()) != -1) {
b[i] = (byte) read;
i++;
}
is.close();
String filePath = savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename();
log.info("临时⽂件保存路径:" + savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename());
OutputStream os = new FileOutputStream(new File(savePath + "/" + "temp" + "_" + buildInfo[0].getOriginalFilename()));// ⽂件原名,如a.txt
os.write(b);
os.flush();
os.close();
topologyIpMacPortRealService.importIpMac(filePath);
} catch (Exception e) {
if (log.isDebugEnabled())
log.debug("系统异常", e);
}
}
Java代码实现层: public int importIpMac(String filePath) throws Exception {
// List dataList=CSVUtils.importCsv(new File("/Users/wjm/Desktop/testexcel.csv")); List dataList = CSVUtils.importCsv(new File(filePath));
if (dataList != null && !dataList.isEmpty()) {
for (int i = 1; i < dataList.size(); i++) {
String data = (i);
SiTopologyIpMacPortBase base = new SiTopologyIpMacPortBase();
String[] source = data.split(",");
if (source[0] != "") {
base.setId(source[0]);
base.setMac(source[1]);
base.setIp(source[2]);
base.setUpIp(source[3]);
base.setUpName(source[4]);
base.setUpIndex(source[5]);
base.setModifyTime(source[6]);
siTopologyIpMacPortBaseDao.insert(base);
}
}
}
return 1;
}
其中CSVUtils类: si.toimplmon.utils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
* CSV操作(导出和导⼊)
*
* @author wjm
* @version 1.0 Nov 24, 2015 4:30:58 PM
*/
public class CSVUtils {
/**
* 导出
*
* @param file csv⽂件(路径+⽂件名),csv⽂件不存在会⾃动创建
* @param dataList 数据
* @return
*/
public static boolean exportCsv(File file, List dataList){
boolean isSucess=false;
FileOutputStream out=null;
OutputStreamWriter osw=null;
BufferedWriter bw=null;
try {
// OutputStreamWriter in_=new OutputStreamWriter(new FileOutputStream("⽂件名"), "gbk"); out = new FileOutputStream(file);
osw = new OutputStreamWriter(out, "gbk");
bw =new BufferedWriter(osw);
if(dataList!=null && !dataList.isEmpty()){
for(String data : dataList){
bw.append(data).append("\r");
}
}
isSucess=true;
} catch (Exception e) {
isSucess=false;
}finally{
if(bw!=null){
bw.close();
bw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(osw!=null){
try {
osw.close();
osw=null;
} catch (IOException e) {
e.printStackTrace();
}
}
if(out!=null){
try {
out.close();
out=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return isSucess;
}
/
**
* 导⼊
*
* @param file csv⽂件(路径+⽂件)
* @return
*/
public static List importCsv(File file){ List dataList=new ArrayList();

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。