[置顶] 使用jxls技术导入Excel模版数据

 

今天接到一个需求,要求我把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,以后有时间再写一篇吧!希望能帮到需要的人,哈哈!有写的不对的希望高手可以指点一下!谢谢!
 

  • 大小: 40 KB
  • 大小: 43.6 KB
  • 大小: 53 KB
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
Jxls 是一个开源的 Java 库,用于导出 Excel 文件,它可以在 Java 中非常方便地进行使用。下面是使用 Jxls 导出 Excel 的步骤: 1. 添加依赖 在 pom.xml 文件中添加以下依赖: ```xml <dependency> <groupId>org.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.15</version> </dependency> ``` 2. 准备 Excel 模板 在 Excel 文件中准备好要导出的内容,包括表头和数据部分。可以在表格中使用 ${} 来标记需要动态替换的数据。 3. 准备数据 在 Java 代码中准备好要导出的数据,可以使用 List 或者 Map 等类型来保存数据。 4. 创建模板引擎 使用 Jxls 提供的模板引擎创建一个模板,可以使用以下代码: ```java InputStream is = new FileInputStream(new File("template.xls")); Workbook workbook = WorkbookFactory.create(is); Transformer transformer = TransformerFactory.createTransformer(workbook, outputStream); ``` 其中,“template.xls”是你准备好的 Excel 模板文件名,outputStream 是导出文件的输出流。 5. 填充数据 使用 Jxls 提供的 API 填充数据,可以使用以下代码: ```java Map<String, Object> beans = new HashMap<>(); beans.put("dataList", dataList); transformer.transformXLS(new HashMap<>(), beans); ``` 其中,“dataList”是你准备好的数据,transformer.transformXLS() 方法将会把数据填充到模板中。 6. 输出文件 使用 Jxls 提供的 API 输出文件,可以使用以下代码: ```java transformer.flush(); outputStream.close(); ``` 这样就可以将 Excel 文件导出到 outputStream 中了。 以上是使用 Jxls 导出 Excel 的基本步骤,你可以根据自己的需求进行更多的调整和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值