JXLS 多个sheet

1.java代码

package com.knife.jxls;

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

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;

import com.knife.jxls.TestJxls.Foo;

public class TestJxlsSheet {

	
	public static class Foo {

		public String id;
		public String name;
		public int age;

		public Foo(String id, String name, int age) {
			this.id = id;
			this.name = name;
			this.age = age;
		}

	}

	public static void main(String args[]) throws IOException {

		List foolist=new ArrayList();
		foolist.add(new Foo("001","lee",11));
		foolist.add(new Foo("002","wang",14));
		foolist.add(new Foo("003","zhang",19));
		
		List sheetNames= new ArrayList();
		sheetNames.add("001");
		sheetNames.add("002");
		sheetNames.add("003");
		
		InputStream in = new FileInputStream("H:\\template.xlsx");
		OutputStream out = new FileOutputStream("H:\\test1.xlsx");
		Context context = new Context();
		context.putVar("foolist", foolist);
		context.putVar("sheetNames", sheetNames);
		JxlsHelper.getInstance().processTemplate(in, out, context);
	}
	
}

2.批注

jx:area(lastCell = "C3")
jx:each(items="foolist", var="foo", lastCell="C3" multisheet="sheetNames")

3.结果

模板:

JXLS 多个sheet_第1张图片

输出文件:

JXLS 多个sheet_第2张图片

此时会多出一个空白sheet

需要重写jslx的一个函数来解决,代码如下:

public void processTemplate(Context context, Transformer transformer) throws IOException {

		AreaBuilder areaBuilder = this.getAreaBuilder();
		boolean processFormulas = this.isProcessFormulas();

		areaBuilder.setTransformer(transformer);
		List xlsAreaList = areaBuilder.build();
		Iterator var4 = xlsAreaList.iterator();

		Area xlsArea;
		while (var4.hasNext()) {
			xlsArea = (Area) var4.next();
			xlsArea.applyAt(new CellRef(xlsArea.getStartCellRef().getCellName()), context);
		}

		if (processFormulas) {
			var4 = xlsAreaList.iterator();

			while (var4.hasNext()) {
				xlsArea = (Area) var4.next();
				this.setFormulaProcessor(xlsArea);
				xlsArea.processFormulas();
			}
		}

		if (this.isDeleteTemplateSheet()) {
			transformer.deleteSheet("Sheet3");
		}

		transformer.write();

	}

 

你可能感兴趣的:(java)