JXLS Demo

阅读更多
JxlsUtil.java
package template;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;

public class JxlsUtil {
	
	/**
	 * 导出excel
	 * @param templateFile - excel模版名称
	 * @param beans - 模版中填充的数据
	 * @param os - 生成模版输出流
	 */
	public static void exportExcel(String templateFile,Map beans,OutputStream os) {
	     XLSTransformer transformer = new XLSTransformer();
	     InputStream is=JxlsUtil.class.getClassLoader().getResourceAsStream(templateFile);
	     try {
			Workbook workbook=transformer.transformXLS(is,beans);
			workbook.write(os);
		} catch (Exception e) {
			throw new RuntimeException("导出excel错误!");
		} 
	}
	
	public static void main(String[] args) throws ParsePropertyException, InvalidFormatException, IOException {
		OutputStream os=new FileOutputStream("new.xls");
		String templateFile="template/jxls_template.xls";
		Map beans=new HashMap();
		
		// fruits
		List> fruitList=new ArrayList>();
		
		Map fruit=null;
		fruit=new HashMap();
		fruit.put("name", "苹果");
		fruit.put("price", "100");
		fruitList.add(fruit);
		
		fruit=new HashMap();
		fruit.put("name", "香蕉");
		fruit.put("price", "200");
		fruitList.add(fruit);
		
		beans.put("fruits",fruitList);
		exportExcel(templateFile, beans, os);
	}
}

template/jxls_template.xls


在使用做循环时,如果 在同一行就可以做横向循环

  • JXLS Demo_第1张图片
  • 大小: 20.5 KB
  • 查看图片附件

你可能感兴趣的:(JXLS Demo)