Java实现根据excel模板导出数据(适合导出结构复杂的excel)

根据模板导出excel适用于表格结构复杂的数据导出,需要提前定义好excel模板,设置好变量,然后导出数据到excel模板中。

在idea中创建一个excel文件

打开创建好的文件province.xls,开始定义模板,设置变量用${}形式,此处的变量要和后边java代码中的model类的字段要一致,这样才能把具体数据输出到excel模板对应的位置。

导入依赖

<!-- jxls poi -->
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls-poi</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>org.jxls</groupId>
    <artifactId>jxls</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>net.sf.jxls</groupId>
    <artifactId>jxls-core</artifactId>
    <version>1.0.6</version>
</dependency>

model类

import lombok.Data;

@Data
public class AreaModel {

    private Integer no;

    private Integer areaCode;

    private String areaName;

    private Integer level;
}

Util类

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

public class TemplateExcelUtils {

	/**
     * 根据模板导出数据
     * @param fileName
     * @param sourcePath resource/template文件夹下路径
     * @param beanParams
     * @param response
     * @throws Exception
     */
    public static void downLoadExcel(String fileName,String sourcePath, Map<String, Object> beanParams, HttpServletResponse response)
            throws Exception {
        try{
            OutputStream os = getOutputStream(fileName,response);
            //读取模板
            InputStream is = TemplateExcelUtils.class.getClassLoader().getResourceAsStream("template/"+sourcePath);
            XLSTransformer transformer = new XLSTransformer();
            //向模板中写入内容
            Workbook workbook = transformer.transformXLS(is, beanParams);
            //写入成功后转化为输出流
            workbook.write(os);
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }

	/**
     * 导出文件时为Writer生成OutputStream.
     * @param fileName 文件名
     * @param response response
     * @return ""
     */
    private static OutputStream getOutputStream(String fileName,
                                                HttpServletResponse response) throws Exception {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");
            return response.getOutputStream();
        } catch (IOException e) {
            throw new Exception("导出excel表格失败!", e);
        }
    }
}

 业务类

	@Override
    public void exportTemplateProvinceAreaData(HttpServletResponse response){
        List<Area> areas = areaMapper.queryProvinceArea();  // 此处是我本地项目的mapper,是为了获取省份数据
        List<AreaModel> result = new ArrayList<>();
        areas.stream().forEach(area -> {
            AreaModel areaModel = new AreaModel();
            BeanUtils.copyProperties(area,areaModel);
            result.add(areaModel);
        });
        IntStream.range(0, result.size()).forEach(i -> {
            result.get(i).setNo(i+1);
        });
        try {
            Map<String,Object> param = new HashMap<>();
            param.put("title","省份数据");
            param.put("list",result);
            TemplateExcelUtils.downLoadExcel("省份数据","province.xls",param,response);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.EXPORT_ERROR);
        }
    }

这是我业务层areaMapper.queryProvinceArea();所返回的省份数据

controller层

@GetMapping("/exportTemplateData")
    public void exportTemplateData(HttpServletResponse response){
        areaService.exportTemplateProvinceAreaData(response);
    }

返回的excel

到这里根据模板导出就做好了。上面是一个比较简单的模板,也可以定义复杂结构的模板

导出的数据。

注意:如果运行时报以下错,org.apache.poi.openxml4j.exceptions:Your InputStream was neither an OLE2 stream, nor an OOXML stream则需要加依赖:

<plugins>
<!-- 让maven不编译xls文件,但仍将其打包 -->
    <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-resources-plugin</artifactId>
           <configuration>
               <nonFilteredFileExtensions>
                   <nonFilteredFileExtension>xls</nonFilteredFileExtension>
               </nonFilteredFileExtensions>
           </configuration>
    </plugin>
</plugins>

根据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导出数据。如果你的数据结构中包含其他类,你可以通过以下步骤实现: 1. **添加依赖**:首先需要将Apache POI及其相关的单元格样式处理库(如XSSF)添加到项目中。如果是Maven项目,可以在pom.xml文件中添加依赖: ```xml <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>5.0.0</version> </dependency> ``` 2. **模型类设计**:对于包含其他类的字段,创建一个自定义对象模型,比如`Order`类,然后在`User`类或其他相关类中引用它: ```java public class User { private String name; private Address address; // 这里假设Address是一个独立的类 private List<Order> orders; // 省略getter和setter } ``` 3. **写入数据**:在导出数据时,你需要将对象模型转换成Excel表格。这通常涉及到遍历对象集合,将每个对象转换成行,并使用`Row`和`Cell`类来填充单元格: ```java // 假设你已经有了一个User对象列表 List<User> userList = ...; for (User user : userList) { Row row = workbook.createRow(rowIndex++); Cell cellName = row.createCell(0); cellName.setCellValue(user.getName()); // 处理地址字段 Row addressRow = row.createCell(1); // 如果地址作为单独的一行 if (user.getAddress() != null) { AddressCell addressCell = new AddressCell(addressRow); addressCell.setAddress(user.getAddress()); } // 处理订单列表 for (Order order : user.getOrders()) { // 同理,将Order转换成对应的Cell对象并添加到row } } ``` 4. **保存文件**:最后,记得保存整个工作簿到指定的Excel文件: ```java workbook.write(new FileOutputStream("output.xlsx")); workbook.close(); ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值