java實(shí)現(xiàn)CSV文件導(dǎo)入與導(dǎo)出功能
年前在開(kāi)發(fā)功能模塊的時(shí)候用到了CSV文件導(dǎo)入導(dǎo)出,就此整理一下,便于大家參考。
導(dǎo)入導(dǎo)出功能很多時(shí)候用到的都是Excel文件,但是現(xiàn)在越來(lái)越多的使用了CSV文件進(jìn)行此操作,它是一個(gè)純文本文件,可以用記事本打開(kāi),也可以用Excel打開(kāi)。CSV文件不像Excel那樣有很多條條框框,它使用硬回車(chē)分割每條記錄,用逗號(hào)分隔每條數(shù)據(jù)的字段。
CSV格式的文件就是用硬回車(chē)和文本都好實(shí)現(xiàn)的表格,用Excel一讀就成了表格。文件名后綴就是 .csv。
直接上代碼吧!
導(dǎo)入部分
導(dǎo)入的時(shí)候基于Ajax請(qǐng)求,js代碼如下:
function importIpMac(upload) {
var importTextInfo = document.getElementById("importTextInfo");
importTextInfo.value="";
$.ajaxFileUpload({
url: ctx + "/ipmac/importIpMac",
type: 'post',
secureuri: false, // 一般設(shè)置為false
fileElementId: 'upload', // 上傳文件的id、name屬性名
dataType: 'text', // 返回值類(lèi)型,一般設(shè)置為json、application/json
success: function(data, status){
getIpMacBase();
},
error: function(data, status, e){
alert('請(qǐng)求異常!');
}
});
}
Java代碼控制層:
/**
* 導(dǎo)入
*/
@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目錄下,不允許外界直接訪(fǎng)問(wèn),保證上傳文件的安全
String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
savePath = savePath.replace("file:", ""); // 去掉file:
File file1 = new File(savePath);
// 判斷上傳文件的保存目錄是否存在
if (!file1.exists() && !file1.isDirectory()) {
log.info(savePath + "目錄不存在,需要?jiǎng)?chuàng)建");
file1.mkdir();
}
// 刪除此路徑下的所有文件以及文件夾
delAllFile(savePath);
try {
InputStream is = buildInfo[0].getInputStream();// 多文件也適用,我這里就一個(gè)文件
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("臨時(shí)文件保存路徑:" + 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("系統(tǒng)異常", e);
}
return 1;
}
Java代碼實(shí)現(xiàn)層:
public int importIpMac(String filePath) throws Exception {
// List<String> dataList=CSVUtils.importCsv(new File("/Users/wjm/Desktop/testexcel.csv"));
List<String> dataList = CSVUtils.importCsv(new File(filePath));
if (dataList != null && !dataList.isEmpty()) {
for (int i = 1; i < dataList.size(); i++) {
String data = dataList.get(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類(lèi):
package com.one.si.toimpl.common.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操作(導(dǎo)出和導(dǎo)入)
*
* @author wjm
* @version 1.0 Nov 24, 2015 4:30:58 PM
*/
public class CSVUtils {
<span style="white-space:pre"> </span>/**
* 導(dǎo)出
*
* @param file csv文件(路徑+文件名),csv文件不存在會(huì)自動(dòng)創(chuàng)建
* @param dataList 數(shù)據(jù)
* @return
*/
public static boolean exportCsv(File file, List<String> 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){
try {
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;
}
/**
* 導(dǎo)入
*
* @param file csv文件(路徑+文件)
* @return
*/
public static List<String> importCsv(File file){
List<String> dataList=new ArrayList<String>();
BufferedReader br=null;
try {
br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
dataList.add(line);
}
}catch (Exception e) {
}finally{
if(br!=null){
try {
br.close();
br=null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
return dataList;
}
}
導(dǎo)出部分
js部分:
/*
* 導(dǎo)出基準(zhǔn)表中的數(shù)據(jù)
*/
function exportIpMac() {
window.open("exportIpMac.do");
}
Java代碼控制層:
/**
* 導(dǎo)出的基準(zhǔn)表信息
*/
@ResponseBody
@RequestMapping("/exportIpMac")
public String exportIpMac(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<String> dataList = topologyIpMacPortRealService.exportIpMac();
response.setCharacterEncoding("GBK");
SimpleDateFormat dfs = new SimpleDateFormat("yyyyMMddHHmmss");// 設(shè)置日期格式
Date time = new Date();
String tStamp = dfs.format(time);
String filename = "IpMacPortExport"+tStamp + ".csv";
response.setHeader("contentType", "text/html; charset=GBK");
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="+filename);
String cp=request.getSession().getServletContext().getRealPath("/");
String path = cp+"download/"+filename;
File file = new File(path);
BufferedInputStream bis = null;
BufferedOutputStream out = null;
FileWriterWithEncoding fwwe =new FileWriterWithEncoding(file,"GBK");
BufferedWriter bw = new BufferedWriter(fwwe);
if(dataList!=null && !dataList.isEmpty()){
for(String data : dataList){
bw.write(data);
bw.write("\n");
}
}
bw.close();
fwwe.close();
try {
bis = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
while (true) {
int bytesRead;
if (-1 == (bytesRead = bis.read(buff, 0, buff.length))){
break;
}
out.write(buff, 0, bytesRead);
}
file.deleteOnExit();
}
catch (IOException e) {
throw e;
}
finally{
try {
if(bis != null){
bis.close();
}
if(out != null){
out.flush();
out.close();
}
}
catch (IOException e) {
throw e;
}
}
delAllFile(cp+"download/");
return null;
}
Java代碼實(shí)現(xiàn)層:
public List<String> exportIpMac() throws Exception {
List<String> dataList = new ArrayList<String>();
try {
List<SiTopologyIpMacPortReal> list = siTopologyIpMacPortRealdao.selectAllData();
dataList.add("ID,地址,IP地址,設(shè)備,設(shè)備名稱(chēng),端口,更新時(shí)間");
for (int i = 0; i < list.size(); i++) {
dataList.add(list.get(i).getId() + "," + list.get(i).getMac()
+ "," + list.get(i).getIp() + ","
+ list.get(i).getUpIp() + ","
+ list.get(i).getUpName() + ","
+ list.get(i).getUpIfIndex() + ","
+ list.get(i).getModifyTime());
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
使用的是Chrome瀏覽器,下載的時(shí)候會(huì)直接在瀏覽器下面進(jìn)行顯示下載。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Maven入門(mén)教程之如何在idea中配置Maven
Maven是非常出色的項(xiàng)目管理工具,我們可以用它管理本地項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Maven入門(mén)教程之如何在idea中配置Maven的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
SpringBoot2零基礎(chǔ)到精通之?dāng)?shù)據(jù)與頁(yè)面響應(yīng)
SpringBoot是一種整合Spring技術(shù)棧的方式(或者說(shuō)是框架),同時(shí)也是簡(jiǎn)化Spring的一種快速開(kāi)發(fā)的腳手架2022-03-03
Java ffmpeg 實(shí)現(xiàn)視頻加文字/圖片水印功能(示例代碼)
本文介紹了使用Java和ffmpeg庫(kù)實(shí)現(xiàn)視頻加文字或圖片水印的方法,通過(guò)引入依賴(lài)代碼和示例,詳細(xì)說(shuō)明了如何將文字水印和圖片水印添加到視頻中,為需要在視頻中加入水印的開(kāi)發(fā)者提供了實(shí)用的指導(dǎo),這種方法不僅增強(qiáng)了視頻內(nèi)容的版權(quán)保護(hù),也為視頻編輯提供了更多的可能性2024-10-10
基于Java創(chuàng)建XML(無(wú)中文亂碼)過(guò)程解析
這篇文章主要介紹了基于Java創(chuàng)建XML(無(wú)中文亂碼)過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10
Spring Cloud Hystrix 線(xiàn)程池隊(duì)列配置(踩坑)
這篇文章主要介紹了Spring Cloud Hystrix 線(xiàn)程池隊(duì)列配置(踩坑),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01
Java入門(mén)基礎(chǔ)之常規(guī)的命名方法和變量的值及其引用
這篇文章主要介紹了Java的命名方法和變量的值及其引用,是Java入門(mén)學(xué)習(xí)中的基礎(chǔ)知識(shí),需要的朋友可以參考下2015-09-09
面向?qū)ο蠛兔嫦蜻^(guò)程的區(qū)別(動(dòng)力節(jié)點(diǎn)java學(xué)院整理)
很多朋友不清楚面向?qū)ο蠛兔嫦蜻^(guò)程有什么區(qū)別,接下來(lái)小編給大家整理了關(guān)于面向?qū)ο蠛兔嫦蜻^(guò)程的區(qū)別講解,感興趣的朋友可以參考下2017-04-04

