JAVA中模板导出excel之JXLS

Java中实现excel根据模板导出数据的方法有很多,一般简单的可以通过操作POI进行。还可以使用一些工具很轻松的实现模板导出。这些工具现在还在维护,而且做得比较好的国内的有easyPOI,国外的就是这个JXLS了。个人觉得easyPOI做动态列导出(不固定列)比较好;JXLS做固定模板导出比较方便。

1. 首先加入JXLS依赖包。

<dependency>
      <groupId>org.jxls</groupId>
      <artifactId>jxls</artifactId>
      <version>2.4.6</version>
      <exclusions>
          <exclusion>
              <groupId>ch.qos.logback</groupId>
              <artifactId>logback-core</artifactId>
          </exclusion>
      </exclusions>
  </dependency>

  <dependency>
      <groupId>org.jxls</groupId>
      <artifactId>jxls-poi</artifactId>
      <version>1.0.15</version>
  </dependency>

  <dependency>
      <groupId>org.jxls</groupId>
      <artifactId>jxls-jexcel</artifactId>
      <version>1.0.7</version>
  </dependency>

2.使用

  1. .在项目中编写util工具类
public class JxlsExcelView extends AbstractView{
	private static final String	CONTENT_TYPE	= "application/vnd.ms-excel";

	private String				templatePath;
	private String				exportFileName;

	/**
	 * @param templatePath
	 *            模版相对于当前classpath路径
	 * @param exportFileName
	 *            导出文件名
	 */
	public JxlsExcelView(String templatePath, String exportFileName)
	{
		this.templatePath = templatePath;
		this.exportFileName = exportFileName;
		setContentType(CONTENT_TYPE);
	}

	@Override
	protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception
	{
		Context context = PoiTransformer.createInitialContext();
		if (model != null)
		{
			for (String key : model.keySet())
			{
				context.putVar(key, model.get(key));
			}
		}
		String userAgent = request.getHeader("user-agent").toLowerCase();
		response.setContentType(getContentType());
		// 防止乱码
		if (userAgent.contains("msie") || userAgent.contains("like gecko"))
		{
			// win10 ie edge 浏览器 和其他系统的ie
			exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
		} else
		{
			exportFileName = new String(exportFileName.getBytes("UTF-8"), "ISO-8859-1");
		}
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-disposition", "attachment;filename=" + exportFileName + ".xlsx");
		ServletOutputStream os = response.getOutputStream();
		Resource resource = new ClassPathResource("/static/xlstemplate/" + templatePath);
		InputStream is = resource.getInputStream();
		JxlsHelper jxlsHelper = JxlsHelper.getInstance();
		Transformer transformer = jxlsHelper.createTransformer(is, os);
		// 获得配置
		JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
		//设置静默模式,不报警告
		evaluator.getJexlEngine().setSilent(true);
		//必须要这个,否者表格函数统计会错乱
		jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer);
		is.close();
	}
}
  1. 在controller中调用方法
@RequestMapping("downloadTeacherTemplate")
	public JxlsExcelView downModel(Model model, HttpServletRequest request)
	{
		try
		{
			model.addAttribute("XB", dictService.queryDict("STD_GB_XB"));
			model.addAttribute("MZ", dictService.queryDict("STD_GB_MZ"));
			model.addAttribute("ZJLX", dictService.queryDict("STD_JB_SFZJLX"));
			model.addAttribute("DQZT", dictService.queryDict("STD_JB_JZGDQZT"));
			// 模版相对于当前classpath路径;导出文件名;
			return new JxlsExcelView("jzgImportTemplate.xlsx", "教职工导入模板");
		} catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
  1. 编写模板jzgImportTemplate.xlsx
    在这里插入图片描述
    我此处是循环的批注写法jx:area(lastCell=“A1”) jx:each(items=“XB” var=“item” lastCell=“A1” )
    如果不循环,就更简单了。直接在所对应单元格中直接写入${XB}此种样式即可。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java通过模板导出Excel可以使用Apache POI和Jxls两种方式。 1. Apache POI Apache POI是一个用于读写Microsoft Office格式文件的Java库。通过POI,可以使用Java代码读取、创建和修改Excel文件、Word文档和PowerPoint演示文稿等Microsoft Office格式文件。 使用POI导出Excel需要先创建Excel模板,然后在Java代码读取模板文件,根据数据填充模板,最后将填充后的数据写入新的Excel文件。 2. Jxls Jxls是一个用于将Java数据导出Excel、Word和PDF等格式文件的开源Java库。Jxls提供了一种基于Excel模板的数据填充方式,可以通过Java对象、Map或List等数据源填充Excel模板,并将填充后的数据写入新的Excel文件。 使用Jxls导出Excel需要先创建Excel模板,然后在Java代码读取模板文件,根据数据填充模板,最后将填充后的数据写入新的Excel文件。 下面是使用Apache POI和Jxls两种方式导出Excel的示例代码: 1. 使用Apache POI导出Excel ```java // 导出Excel模板 public void exportExcelTemplate(String templateFilePath, String destFilePath) throws Exception { InputStream is = new FileInputStream(templateFilePath); Workbook workbook = WorkbookFactory.create(is); Sheet sheet = workbook.getSheetAt(0); // 在模板填充数据 // ... OutputStream os = new FileOutputStream(destFilePath); workbook.write(os); os.close(); is.close(); } // 导出Excel数据 public void exportExcelData(String templateFilePath, String destFilePath, List<Map<String, Object>> dataList) throws Exception { InputStream is = new FileInputStream(templateFilePath); Workbook workbook = WorkbookFactory.create(is); Sheet sheet = workbook.getSheetAt(0); // 在模板填充数据 for (int i = 0; i < dataList.size(); i++) { Row row = sheet.createRow(i + 1); Map<String, Object> data = dataList.get(i); row.createCell(0).setCellValue(data.get("name").toString()); row.createCell(1).setCellValue(data.get("age").toString()); // ... } OutputStream os = new FileOutputStream(destFilePath); workbook.write(os); os.close(); is.close(); } ``` 2. 使用Jxls导出Excel ```java // 导出Excel模板 public void exportExcelTemplate(String templateFilePath, String destFilePath) throws Exception { InputStream is = new FileInputStream(templateFilePath); OutputStream os = new FileOutputStream(destFilePath); Context context = new Context(); JxlsHelper.getInstance().processTemplate(is, os, context); os.close(); is.close(); } // 导出Excel数据 public void exportExcelData(String templateFilePath, String destFilePath, List<Map<String, Object>> dataList) throws Exception { InputStream is = new FileInputStream(templateFilePath); OutputStream os = new FileOutputStream(destFilePath); Context context = new Context(); context.putVar("dataList", dataList); JxlsHelper.getInstance().processTemplate(is, os, context); os.close(); is.close(); } ``` 以上是两种方式导出Excel的示例代码,其使用Jxls导出Excel需要在项目添加jxlsjxls-poi依赖

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值