Java程式設計之CSV檔案匯入與匯出的實現
阿新 • • 發佈:2019-01-23
年前在開發功能模組的時候用到了CSV檔案匯入匯出,就此整理一下,便於大家參考。
匯入匯出功能很多時候用到的都是Excel檔案,但是現在越來越多的使用了CSV檔案進行此操作,它是一個純文字檔案,可以用記事本開啟,也可以用Excel開啟。CSV檔案不像Excel那樣有很多條條框框,它使用硬回車分割每條記錄,用逗號分隔每條資料的欄位。
CSV格式的檔案就是用硬回車和文字都好實現的表格,用Excel一讀就成了表格。檔名字尾就是 .csv。
直接上程式碼吧!
匯入部分
匯入的時候基於Ajax請求,js程式碼如下:
function importIpMac(upload) { var importTextInfo = document.getElementById("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程式碼控制層:
/** * 匯入 */ @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 + "目錄不存在,需要建立"); 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); } return 1; }
Java程式碼實現層:
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操作(匯出和匯入)
*
* @author wjm
* @version 1.0 Nov 24, 2015 4:30:58 PM
*/
public class CSVUtils {
<span style="white-space:pre"> </span>/**
* 匯出
*
* @param file csv檔案(路徑+檔名),csv檔案不存在會自動建立
* @param dataList 資料
* @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;
}
/**
* 匯入
*
* @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;
}
}
匯出部分
js部分:
/*
* 匯出基準表中的資料
*/
function exportIpMac() {
window.open("exportIpMac.do");
}
Java程式碼控制層:
/**
* 匯出的基準表資訊
*/
@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");// 設定日期格式
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程式碼實現層:
public List<String> exportIpMac() throws Exception {
List<String> dataList = new ArrayList<String>();
try {
List<SiTopologyIpMacPortReal> list = siTopologyIpMacPortRealdao.selectAllData();
dataList.add("ID,地址,IP地址,裝置,裝置名稱,埠,更新時間");
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瀏覽器,下載的時候會直接在瀏覽器下面進行顯示下載。