使用JXLS+Excel模板制作灵活的excel导出

前期一直卡在模板的批注上,改了很多遍的模板批注最终才成功导入,记录下方便以后寻找。

话不多说直接上代码:

Report

package com.example.jxls.common;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Report {

	private static final Logger logger = LoggerFactory.getLogger(Report.class);

	public void createDocument(OutputStream outStream, String templateName, Map<String, Object> data) {
		logger.debug("Start creation of document");

		String pathTemplateName = ("/reports/").concat(templateName).concat(".xls");
		try(InputStream input = this.getClass().getResourceAsStream(pathTemplateName)) {//1
		
            Context context = new Context();
            
            for (Entry<String, Object> element : data.entrySet()) { // 2
            	context.putVar(element.getKey(), element.getValue());
			}
//			System.out.println("context = " + context);
            JxlsHelper.getInstance().processTemplate(input, outStream, context); // 3

		} catch (Exception exception) {
			logger.error("Fail to generate the document", exception);
		} finally {
			closeAndFlushOutput(outStream); // 4
		}
	}

	private void closeAndFlushOutput(OutputStream outStream) {
		try {
			outStream.flush();
			outStream.close();
		} catch (IOException exception) {
			logger.error("Fail to flush and close the output", exception);
		}
	}
}

 

CommonDao

 

package com.example.jxls.dao;

import com.example.jxls.model.Client;
import com.github.javafaker.Faker;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class CommonDao {
	
	public List<Client> getAllClients() {
		
		List<Client> clients = new ArrayList<>();
		Faker faker = new Faker();

		for (int i = 0; i < 20; i++) {
			clients.add(new Client(faker.name().firstName(), 
					faker.name().lastName(), 
					faker.bool().bool(),
					"SSN",
					faker.idNumber().ssnValid(),
					BigDecimal.valueOf(faker.number().numberBetween(1, 100000))));
		}
		
		return clients;
	}
}

UserTask

package com.example.jxls.model;

import lombok.Data;


public class UserTask {
    //用户id
    private String id;
    //用户名称
    private String userName;
    //任务Id
    private String taskId;
    //插件id
    private String  plugId;
    //班级id
    private String  classId;

    public UserTask(String id, String userName, String taskId, String plugId, String classId) {
        this.id = id;
        this.userName = userName;
        this.taskId = taskId;
        this.plugId = plugId;
        this.classId = classId;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getTaskId() {
        return taskId;
    }

    public void setTaskId(String taskId) {
        this.taskId = taskId;
    }

    public String getPlugId() {
        return plugId;
    }

    public void setPlugId(String plugId) {
        this.plugId = plugId;
    }

    public String getClassId() {
        return classId;
    }

    public void setClassId(String classId) {
        this.classId = classId;
    }
}

CommonService

package com.example.jxls.service;

import com.example.jxls.common.Report;
import com.example.jxls.dao.CommonDao;
import com.example.jxls.model.UserTask;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class CommonService {
	
	private CommonDao dao;
	
	public CommonService() {
		dao = new CommonDao();
	}
	
	private void createCommonClientReport(String templateName, String outputName) throws FileNotFoundException, ParseException {
		Report report = new Report();
		
		OutputStream outStream = new FileOutputStream(outputName);
		List<UserTask> employees = generateSampleEmployeeData();
		Map<String, Object> data = new HashMap<>();
//		data.put("createdAt", "2021-01-01");
//		data.put("clients", dao.getAllClients());
		data.put("employees", employees);
		data.put("nowdate", new Date());
		data.put("data2", "222222qwer");
		report.createDocument(outStream, templateName, data);
	}
	public static List<UserTask> generateSampleEmployeeData() throws ParseException {
		List<UserTask> employees = new ArrayList<UserTask>();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd", Locale.US);
		employees.add( new UserTask("2L", "1970-Jul-10", "1500L", "0.15", "1500L") );
		employees.add( new UserTask("3L", "1973-Apr-30", "2300L", "0.15","2300L") );
		employees.add( new UserTask("4L", "1975-Oct-05", "2500L", "0.15","2500L") );
		employees.add( new UserTask("5L", "1978-Jan-07", "1700L", "0.15","1700L") );
		employees.add( new UserTask("6L", "1969-May-30", "2800L", "0.15","2800L") );
		return employees;
	}
	public void createClientReport1() throws FileNotFoundException, ParseException {
		createCommonClientReport("clientsTemplate", "target/clients.xls");
	}
	public void createClientReport2() throws FileNotFoundException, ParseException {
		createCommonClientReport("2111", "target/clients3.xls");
	}
	
//	public void createClientReportWithConditions() throws FileNotFoundException, ParseException {
//		createCommonClientReport("clientsMarkInactiveTemplate", "target/clientsMarkInactive.xls");
//	}
}

Application

package com.example.jxls;

import com.example.jxls.service.CommonService;

import java.io.FileNotFoundException;
import java.text.ParseException;

public class Application {

	public static void main(String[] args) throws FileNotFoundException, ParseException {
		CommonService service = new CommonService();
		
		service.createClientReport2();
		
//		service.createClientReportWithConditions();
	}

}

demo1模板示例:

jx:area(lastCell=”D4“)

效果展示:

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
jxls是一个开源的Java工具,可以根据Excel模板文件生成Excel文件。jxls支持复杂的Excel模板,可以在模板中包含多个工作表、多个单元格样式、公式等。 下面是使用jxls导出Excel的步骤: 1. 创建Excel模板文件,可以使用Excel或者其他电子表格软件创建,也可以使用jxls提供的Excel模板文件样例。 2. 在Java代码中使用jxls API读取Excel模板文件,并将要填充到Excel文件中的数据传递给jxls。 3. 在Excel模板文件中,使用jxls提供的标记语言标记待填充的单元格或区域。 4. 使用jxls API将填充好数据的Excel文件输出到指定位置。 下面是一个简单的示例: 1. 创建Excel模板文件,假设文件名为template.xlsx,包含两个工作表Sheet1和Sheet2,每个工作表中包含一个表格,表格中包含两个单元格A1和B1,A1单元格中填充姓名,B1单元格中填充年龄。 2. 在Java代码中,使用jxls API读取Excel模板文件,准备要填充到Excel文件中的数据: ```java InputStream is = new FileInputStream(new File("template.xlsx")); OutputStream os = new FileOutputStream(new File("output.xlsx")); Map<String, Object> model = new HashMap<String, Object>(); List<Person> persons = new ArrayList<Person>(); persons.add(new Person("Alice", 25)); persons.add(new Person("Bob", 30)); model.put("persons", persons); ``` 3. 在Excel模板文件中,使用jxls提供的标记语言标记待填充的单元格或区域。在A1单元格中插入${person.name},在B1单元格中插入${person.age},表示在Excel文件中填充persons集合中的每个Person对象的name和age属性。 4. 使用jxls API将填充好数据的Excel文件输出到指定位置: ```java XLSTransformer transformer = new XLSTransformer(); Workbook workbook = transformer.transformXLS(is, model); workbook.write(os); os.flush(); os.close(); is.close(); ``` 这样,就可以根据复杂模板导出Excel文件了。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kokotao

你的鼓励就是的创作的最大动力,

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值