Java基于Jxls 1.x导出Excel

第一步:

准备工作:下载所需jar.

 核心jar:   jxls-core-1.0.6.jar 

依赖jar:   poi-3.10-FINAL.jar

依赖jar: poi-ooxml-3.10-FINAL.jar

依赖jar:  commons-jexl-2.0.1.jar

依赖jar:  commons-beanutils-core-1.8.3.jar

依赖jar: commons-collections-3.2.1.jar

依赖jar: commons-digester-2.0.jar

依赖jar:  commons-logging-1.2.jar

以下jar均可在https://mvnrepository.com/下载到,需要注意的是,jar之间相互依赖和版本匹配,版本过高或过低均有可能造成excel导不出,或导出后没数据,打不开文件等问题。以上依赖基于mvnrepository(如下图),事实证明,以上任意jar缺失将导致导出不能正常进行。

第二步:把下载好的jar导入项目,使用Maven的配置好pom.xml,就可以进行编码工作了,以下是导出Excel的工具类:

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.stereotype.Component;

import net.sf.jxls.exception.ParsePropertyException;
import net.sf.jxls.transformer.XLSTransformer;

/**
 * 导出excel的工具类
 *
 */
@Component
public class ExcelExportUtil {

	/**
	 * excel导出实现方法
	 *
	 * @param srcFilePath
	 *            模板xls或xlsx文件路径
	 * @param list1
	 *            模板xls中对应要用到的集合;
	 * @param list2
	 *            模板xls中对应要用到的集合;
	 * @param destFilePath
	 *            生成的xls或xlsx文件路径;
	 * @date 2018年7月24日 下午6:29:14
	 */
	public void createExcel(String srcFilePath, List<?> list1, List<?> list2, String destFilePath) {
		/* ********我们也可以使用相对路径来定位 读取模板文件,或放置生成的文件******** */
		// 根据类加载器,获取URL
		// URL url = this.getClass().getClassLoader().getResource("");
		// 获取到项目的classes目录(如:'E:/jxls/ExportExcelByTemplate/target/classes/')
		// String srcPath = url.getPath();
		/* ********************************************************* */
		
		// 创建XLSTransformer对象
		XLSTransformer transformer = new XLSTransformer();
		Map<String, Object> beanParams = new HashMap<String, Object>();
		// 将要用到的list集合,按对应模板中的名字,放入map中
		beanParams.put("list1", list1);
		beanParams.put("list2", list2);
		try {
			// 生成Excel文件
			transformer.transformXLS(srcFilePath, beanParams, destFilePath);
		} catch (ParsePropertyException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		}
	}
}

测试类:

	public static void main(String[] args) {
		// xls模板全限定名
		String templateFileName = "E:\\Jxls\\template.xls";
		// 生成的xls全限定名
		String destFileName = "E:\\Jxls\\result.xls";

		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

		Map<String, Object> map1 = new HashMap<String, Object>();
		map1.put("name", "u1");
		map1.put("age", 11);
		map1.put("gender", "男");
		map1.put("motto", "我是u1~");

		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("name", "u2");
		map2.put("age", 12);
		map2.put("gender", "男");
		map2.put("motto", "我是u2~");

		Map<String, Object> map3 = new HashMap<String, Object>();
		map3.put("name", "u3");
		map3.put("age", 13);
		map3.put("gender", "男");
		map3.put("motto", "我是u3~");

		Map<String, Object> map4 = new HashMap<String, Object>();
		map4.put("name", "u4");
		map4.put("age", 14);
		map4.put("gender", "男");
		map4.put("motto", "我是u4~");

		list.add(map1);
		list.add(map2);
		list.add(map3);
		list.add(map4);
		// 调用工具
		new ExcelExportUtil().createExcel(templateFileName, list, list, destFileName);
	}

下面是模板Excel:

经此就可以导出Excel文件到指定目录并打开了。

下面再分享下稍微复杂的Excel,应用场景为页面上点击导出数据,就可将数据导出到本地的做法,

下面是模板:(注:红字和箭头是编写模板的提示,非模板中的内容)

后台代码:

@RequestMapping("/getExcel")
public void getExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 准备数据
		List<PhysicalParam> list = getParams(); //该方法调用本类中一个独立的方法获取list集合数据
		//设置导出文件名字
        String destFileName= "destFileName.xls";
        //模板数据  templateExcel为项目中WebRoot下新建的文件夹,用来存放模板文件
        String templateFileName=request.getSession().getServletContext().getRealPath("/templateExcel/template-healthExam.xls");
        Map<String,Object> beans = new HashMap<String,Object>();
        beans.put("list", list);
        XLSTransformer transformer = new XLSTransformer();
        InputStream in=null;
        OutputStream out=null;
        //设置响应
        response.setHeader("Content-Disposition", "attachment;filename=" + destFileName);
        response.setContentType("application/vnd.ms-excel");
        try {
            in=new BufferedInputStream(new FileInputStream(templateFileName));
            Workbook workbook=transformer.transformXLS(in, beans);
            out=response.getOutputStream();
            //将内容写入输出流并把缓存的内容全部发出去
            workbook.write(out);
            out.flush();
        } catch (InvalidFormatException e) {
        	log.error(e.getMessage(), e);
            e.printStackTrace();
        } catch (IOException e) {
        	log.error(e.getMessage(), e);
            e.printStackTrace();
        } finally {
            if (in!=null){try {in.close();} catch (IOException e) {}}
            if (out!=null){try {out.close();} catch (IOException e) {}}
        }

	}

导出的的excel效果图(截图)如下:

在这里特别感谢博友https://blog.csdn.net/justry_deng/article/details/81190244的帮助

猜你喜欢

转载自blog.csdn.net/shenxiaomo1688/article/details/94722074