java根据Excel模板导出excel

本文介绍如何使用jXLS库实现基于模板的Excel数据填充与导出功能,包括Maven项目的依赖配置及非Maven项目的jar包下载链接,并提供了一个具体的示例代码,演示了如何从数据库获取数据并填充到指定的Excel模板中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好久之前做的功能,现在项目又有这个需求,故在此记录一下。

需要jar包:

如果是 maven项目需要引入下面这个就可以

<dependency>
          <groupId>net.sf.jxls</groupId>
          <artifactId>jxls-core</artifactId>
          <version>1.0.3</version>
      </dependency>

如果不是maven:https://download.youkuaiyun.com/download/mufeng633/11097086

伪代码:

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

public Object exportToProveExcel(){
	    try {
		    Map<String, String> dataMap = getService().selectdatas(dataId, tableId);
		    //下载文件
		    if (dataMap.size() > 0 ) {
			    String currntTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
			    Map<String,Object> cMap = new HashMap();
			    Map<String,Object> messMap = new HashMap();
			    //结婚证明Excel模板
			    String srcFilePath = ServletActionContext.getServletContext().getRealPath("WEB-INF/template/结婚证明(A4)0921 (1).xls");
			    String newFileName = "结婚证明 "+currntTime;
			    messMap.put("man",dataMap.get("MAN"));      //男方姓名
			    messMap.put("woman",dataMap.get("WOMAN"));  //女方姓名
			    cMap.put("vms", messMap);

			    HttpServletResponse response = ServletActionContext.getResponse();
			    response.reset();
			    response.setContentType("application"+ File.separator+"vnd.ms-excel");   //下载文版类型
			    response.addHeader("Content-Disposition", "attachment;filename="+new String( newFileName.getBytes("gb2312"), "ISO8859-1" )+".xls");
			    //生成的临时导出文件
			    File destFile = File.createTempFile(newFileName, ".xls");

			    //  开始转换。利用  transformer 转到Excel
			    XLSTransformer transformer = new XLSTransformer();
			    // 参数:srcFilePath:模板源文件    cMap:需要导出的数据   destFile.getAbsolutePath():下载的目标文件
			    transformer.transformXLS(srcFilePath, cMap, destFile.getAbsolutePath());
			    
			    FileInputStream fis = new FileInputStream(destFile);
			    ServletOutputStream out = response.getOutputStream();
			    byte[] bytes = new byte[512];
			    int i = 0;
			    while ((i = fis.read(bytes))  !=-1){
				    out.write(bytes,0,i);
			    }
			    out.close();
			    fis.close();
			    destFile.delete();
		    }

	    }catch (Exception e){
		    e.printStackTrace();
		    throw new RuntimeException(e.getMessage());
	    }
	    return new DefaultHttpHeaders(SUCCESS).disableCaching();
    }

Excel模板为:
其中,vms就是外层cMap的键

如果需要循环,则可以这样:
添加循环体代码:

<jx:forEach items = "${vms}" var="var"> 
		${var.UserName}
</jx:forEach>

其中: vms为外层的键
如:
在这里插入图片描述

最后导出的文件
在这里插入图片描述

到此 完成。

根据excel模板动态导出数据库数据 package text; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletContext; import net.sf.jxls.transformer.XLSTransformer; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; public class TextAction extends ActionSupport { /** */ private static final long serialVersionUID = 1L; private String filename; @SuppressWarnings("rawtypes") public String export() throws Exception { String templateFile = "18.xls"; // String sql = "select * from t_ry order by rybm"; // exportAndDownload(templateFile, DataBase.retrieve(sql)); List datas = new ArrayList(); @SuppressWarnings("unchecked") HashMap map = new HashMap(); map.put("name", "1111"); datas.add(map); exportAndDownload(templateFile, datas); return SUCCESS; } @SuppressWarnings({ "rawtypes", "unchecked" }) public void exportAndDownload(String templateFile, List datas) { try { filename = UUID.randomUUID() + templateFile; // FacesContext context = FacesContext.getCurrentInstance(); // ServletContext servletContext = (ServletContext) // context.getExternalContext().getContext(); ServletContext servletContext = ServletActionContext .getServletContext(); String path = servletContext.getRealPath("\\ExcelFile"); String srcFilePath = path + "\\template\\" + templateFile; String destFilePath = path + "\\download\\" + filename; Map beanParams = new HashMap(); beanParams.put("results", datas); XLSTransformer transfer = new XLSTransformer(); transfer.transformXLS(srcFilePath, beanParams, destFilePath); // Browser.execClientScript("window.location.href='../ExcelFile/downloadfile.jsp?filename=" // + destFile + "';"); } catch (Exception e) { e.printStackTrace(); } } public String getFilename() { return filename; } public void setFilename(String filename) { this.filename = filename; } }
Java中,你可以使用Apache POI库来处理Excel文件,包括读取模板和生成新的工作簿。下面是一个基本的示例,展示了如何根据Excel模板导出数据。请注意,这个例子假设你已经有了一个模板文件和预定义的数据结构。 ```java import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.FileOutputStream; import java.io.IOException; public class ExcelExporter { private static final String TEMPLATE_FILE_PATH = "path_to_your_template.xlsx"; private static final String OUTPUT_FILE_PATH = "path_to_output.xlsx"; public static void main(String[] args) throws IOException { // 加载模板 FileInputStream inputStream = new FileInputStream(TEMPLATE_FILE_PATH); Workbook workbookTemplate = new XSSFWorkbook(inputStream); // 创建新的工作簿 Workbook workbookOutput = new XSSFWorkbook(); // 获取模板的工作表 Sheet sheetTemplate = workbookTemplate.getSheetAt(0); // 创建新的工作表并获取引用 Sheet sheetOutput = workbookOutput.createSheet(); Row rowOutput = sheetOutput.createRow(0); // 新的一行 // 假设模板的第一行是标题,从第二行开始获取数据 int rowIndex = 1; while (rowIndex < sheetTemplate.getLastRowNum()) { Row templateRow = sheetTemplate.getRow(rowIndex++); // 复制模板行到新工作表 copyRow(templateRow, rowOutput); // 添加更多的行... (这里省略) } // 关闭流 inputStream.close(); // 将新工作簿写入文件 try (FileOutputStream outputStream = new FileOutputStream(OUTPUT_FILE_PATH)) { workbookOutput.write(outputStream); } // 释放资源 workbookOutput.close(); } private static void copyRow(Row sourceRow, Row destinationRow) { for (Cell cell : sourceRow.getCells()) { Cell destinationCell = destinationRow.createCell(cell.getColumnIndex()); switch (cell.getCellType()) { // 处理不同类型的数据 case STRING: destinationCell.setCellValue(cell.getStringCellValue()); break; case NUMERIC: destinationCell.setCellValue(cell.getNumericCellValue()); break; case BOOLEAN: destinationCell.setCellValue(cell.getBooleanCellValue()); break; default: destinationCell.setCellValue(cell.getStringCellValue()); // 默认字符串处理 } } } } ```
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值