今天接到一個需求,要求我把Excel中的數據導入java程序中作爲查詢條件,查詢數據在做業務邏輯處理,剛接到任務第一反應用poi解析Excel獲取數據,後來想想,我們的項目中之前導出都是用的jxls實現,而且還挺方便的jxls還有自己的標籤(雖然標籤有點坑),就想着有導出功能jxls肯定也有導入功能啦!嘗試使用jxls導入,發現確實比我以前用poi自己手寫方便多了,下面是部分代碼及過程說明!
第一步:先確定好Excel導入的格式以及各表格字段值的含義
第二步:定義好解析的XML--videoConfig.xml
<?xml version="1.0" encoding="UTF-8"?> <workbook> <worksheet name="Sheet1"> <section startRow="0" endRow="0"/> <loop startRow="1" endRow="1" items="videoInfoList" var="videoInfo" varType="com.iflytek.weike.job.bo.VideoInfo"> <section startRow="1" endRow="1"> <mapping row="1" col="0">videoInfo.index</mapping> <mapping row="1" col="1">videoInfo.videoName</mapping> <mapping row="1" col="2">videoInfo.resourceId</mapping> <mapping row="1" col="3">videoInfo.upload</mapping> <mapping row="1" col="4">videoInfo.content</mapping> <mapping row="1" col="5">videoInfo.schoolName</mapping> </section> <loopbreakcondition> <rowcheck offset="0"> <cellcheck offset="0"></cellcheck> </rowcheck> </loopbreakcondition> </loop> </worksheet> </workbook>
第三步:生成一下解析的實體類VideoInfo(這個需要根據excel文件的列去手工寫一個)
public class VideoInfo { //序號 private int index; //視頻名稱(全稱) private String videoName; //視頻資源ID private String resourceId; //上傳者 private String upload; //課程說明 private String content; //學校名稱 private String schoolName; public VideoInfo() { } public VideoInfo(int index, String videoName, String resourceId, String upload, String content, String schoolName) { super(); this.index = index; this.videoName = videoName; this.resourceId = resourceId; this.upload = upload; this.content = content; this.schoolName = schoolName; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public String getVideoName() { return videoName; } public void setVideoName(String videoName) { this.videoName = videoName; } public String getResourceId() { return resourceId; } public void setResourceId(String resourceId) { this.resourceId = resourceId; } public String getUpload() { return upload; } public void setUpload(String upload) { this.upload = upload; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getSchoolName() { return schoolName; } public void setSchoolName(String schoolName) { this.schoolName = schoolName; } @Override public String toString() { return "VideoInfo [index=" + index + ", videoName=" + videoName + ", resourceId=" + resourceId + ", upload=" + upload + ", content=" + content + ", schoolName=" + schoolName + "]"; } }
第四步:添加jxls的jar包,我這裏項目用maven管理jar包的版本是1.0.6大家可以去下面這個maven資源庫下 載jar包 maven資源庫地址:http://mvnrepository.com/open-source/excel-libraries;
第五步:windows彈框選擇文件並解析Excel數據,這個windows文件框選擇文件我以前還是真沒做過在網上 找了一個很好用的方法請看代碼:
/**
* 打開文件選擇窗口選擇導入文件
* @return 返回文件路徑
* @throws Exception
*/
public String getExcelPath() throws Exception{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
JFileChooser jFileChooser=new JFileChooser();
int i = jFileChooser.showOpenDialog(null);
if(i== jFileChooser.APPROVE_OPTION){ //打開文件
String path = jFileChooser.getSelectedFile().getAbsolutePath();
String fileName = jFileChooser.getSelectedFile().getName();
String extName =fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
System.out.println("當前文件路徑:"+path+";\n當前文件名:"+fileName+";\n當前文件擴展名:"+extName);
if(null!=extName&&"xlsx".equals(extName)){
return path;
}else{
System.out.println("您好,只能導入擴展名爲xlsx的Excel文件!");
return null;
}
}else{
System.out.println("沒有選中文件");
return null;
}
}
/**
* 使用jxls解析導入的Excel
* @param path 導入文件路徑
* @return List<VideoInfo> 導入對象集合
*/
public List<VideoInfo> getExcelDataForVideoInfo(String path){
List<VideoInfo> videoInfoList = new ArrayList<VideoInfo>();
try {
InputStream inputXML = new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(ConsForSystem.XML_CONFIG));
XLSReader mainReader = ReaderBuilder.buildFromXML( inputXML );
InputStream inputXLS = new BufferedInputStream(new FileInputStream(new File(path)));
VideoInfo videoInfo = new VideoInfo();
Map<String,Object> beans = new HashMap<String,Object>();
beans.put("videoInfo", videoInfo);
beans.put("videoInfoList", videoInfoList);
XLSReadStatus readStatus = mainReader.read( inputXLS, beans);
if(readStatus.isStatusOK()){
System.out.println("jxls讀取Excel成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
return videoInfoList;
}
其中有個靜態變量我是統一寫在配置類中的:
public static String XML_CONFIG ="videoConfig.xml";
第六步:寫一個main函數執行我們寫好的方法試一下
public class Test {
public static void main(String[] args) {
SyncDataServiceImpl syncDataService = new SyncDataServiceImpl();
try {
String filePath = syncDataService.getExcelPath();
if(null!=filePath&&StringUtils.isNotBlank(filePath)){
//導入Excel文件解析信息獲取資源id
List<VideoInfo> infoList = syncDataService.getExcelDataForVideoInfo(filePath);
System.out.println("infoList大小==="+infoList.size());
for(VideoInfo video:infoList){
System.out.println("打印ideoInfo詳細信息======"+video.toString());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
其中SyncDataServiceImpl類是我把前面二個方法寫到這個類裏面了,裏面還有一些其他的業務處理邏輯,就不貼上來了, new SyncDataServiceImpl()對象就可以調用剛纔的方法了!
下面的運行截圖:
運行結果截圖,導入Excel成功:
相比較POI來讀取Excel數據個人覺得jxls用起來還是更方便一點!同時jxls導出Excel也是比較方便的,有自己的標籤類似JSTL,以後有時間再寫一篇吧!希望能幫到需要的人,哈哈!有寫的不對的希望高手可以指點一下!謝謝!