欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實(shí)現(xiàn)CSV文件導(dǎo)入與導(dǎo)出功能

 更新時(shí)間:2020年12月31日 10:49:31   作者:山景  
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)CSV文件導(dǎo)入與導(dǎo)出,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

年前在開發(fā)功能模塊的時(shí)候用到了CSV文件導(dǎo)入導(dǎo)出,就此整理一下,便于大家參考。

導(dǎo)入導(dǎo)出功能很多時(shí)候用到的都是Excel文件,但是現(xiàn)在越來越多的使用了CSV文件進(jìn)行此操作,它是一個(gè)純文本文件,可以用記事本打開,也可以用Excel打開。CSV文件不像Excel那樣有很多條條框框,它使用硬回車分割每條記錄,用逗號(hào)分隔每條數(shù)據(jù)的字段。

CSV格式的文件就是用硬回車和文本都好實(shí)現(xiàn)的表格,用Excel一讀就成了表格。文件名后綴就是 .csv。

直接上代碼吧!

導(dǎo)入部分

導(dǎo)入的時(shí)候基于Ajax請求,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', // 返回值類型,一般設(shè)置為json、application/json
 success: function(data, status){
 getIpMacBase();
 },
 error: function(data, status, e){
 alert('請求異常!');
 }
 });
}

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目錄下,不允許外界直接訪問,保證上傳文件的安全
 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類:

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è)備名稱,端口,更新時(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)行顯示下載。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Springboot?jpa使用sum()函數(shù)返回結(jié)果如何被接收

    Springboot?jpa使用sum()函數(shù)返回結(jié)果如何被接收

    這篇文章主要介紹了Springboot?jpa使用sum()函數(shù)返回結(jié)果如何接收,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • feign實(shí)現(xiàn)傳遞參數(shù)的三種方式小結(jié)

    feign實(shí)現(xiàn)傳遞參數(shù)的三種方式小結(jié)

    這篇文章主要介紹了feign實(shí)現(xiàn)傳遞參數(shù)的三種方式小結(jié),具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • 詳解Maven settings.xml配置(指定本地倉庫、阿里云鏡像設(shè)置)

    詳解Maven settings.xml配置(指定本地倉庫、阿里云鏡像設(shè)置)

    這篇文章主要介紹了詳解Maven settings.xml配置(指定本地倉庫、阿里云鏡像設(shè)置),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-12-12
  • Java OSS批量下載并壓縮為ZIP代碼實(shí)例

    Java OSS批量下載并壓縮為ZIP代碼實(shí)例

    這篇文章主要介紹了Java OSS批量下載并壓縮為ZIP代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • SpringBoot接口接收json參數(shù)解析

    SpringBoot接口接收json參數(shù)解析

    這篇文章主要介紹了SpringBoot接口接收json參數(shù)解析,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • Java 線程池ExecutorService詳解及實(shí)例代碼

    Java 線程池ExecutorService詳解及實(shí)例代碼

    這篇文章主要介紹了Java 線程池ExecutorService詳解及實(shí)例代碼的相關(guān)資料,線程池減少在創(chuàng)建和銷毀線程上所花的時(shí)間以及系統(tǒng)資源的開銷.如果不使用線程池,有可能造成系統(tǒng)創(chuàng)建大量線程而導(dǎo)致消耗系統(tǒng)內(nèi)存以及”過度切換“
    2016-11-11
  • SpringBoot整合mybatis-generator插件流程詳細(xì)講解

    SpringBoot整合mybatis-generator插件流程詳細(xì)講解

    這篇文章主要介紹了SpringBoot整合mybatis-generator插件流程,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧
    2023-02-02
  • SpringBoot使用Quartz無法注入Bean的問題及解決

    SpringBoot使用Quartz無法注入Bean的問題及解決

    這篇文章主要介紹了SpringBoot使用Quartz無法注入Bean的問題及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • 解決java.lang.Error: Unresolved compilation problems:問題

    解決java.lang.Error: Unresolved compilation pro

    這篇文章主要介紹了解決java.lang.Error: Unresolved compilation problems:問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • Java多線程中的互斥鎖解析

    Java多線程中的互斥鎖解析

    這篇文章主要介紹了Java多線程中的互斥鎖解析,Java語言中,引入了對象互斥鎖的概念,來保證共享數(shù)據(jù)操作的完整性,每個(gè)對象都對應(yīng)于一個(gè)可稱為互斥鎖的標(biāo)記,這個(gè)標(biāo)記用來保證在任一時(shí)刻,只能有一個(gè)線程訪問該對象,需要的朋友可以參考下
    2023-09-09

最新評(píng)論