Hutool导出Excel,导多个Sheet页

重要方法

// 指定要写出的 Sheet 页
bigWriter.setSheet(sheet.getSheetName());

工具类

public class HuExcelUtils {
    
    /** 
     * 导出多个 Sheet 页
     * @param response
     * @param sheetList 页数据
     * @param fileName 文件名
     */
    public static void exportExcel(HttpServletResponse response, List<SheetDTO> sheetList, String fileName) {
        ExcelWriter bigWriter = ExcelUtil.getBigWriter();
        // 重命名第一个Sheet的名称,不然会默认多出一个Sheet1的页
        bigWriter.renameSheet(0, sheetList.get(0).getSheetName());
        for (SheetDTO sheet : sheetList) {
            // 指定要写出的 Sheet 页
            bigWriter.setSheet(sheet.getSheetName());
            Integer[] columnWidth = sheet.getColumnWidth();
            if (columnWidth == null || columnWidth.length != sheet.getFieldAndAlias().size()) {
                // 设置默认宽度 
                for (int i = 0; i < sheet.getFieldAndAlias().size(); i++) {
                    bigWriter.setColumnWidth(i, 25);
                }
            } else {
                // 设置自定义宽度 
                for (int i = 0; i < columnWidth.length; i++) {
                    bigWriter.setColumnWidth(i, columnWidth[i]);
                }
            }
            // 设置字段和别名
            bigWriter.setHeaderAlias(sheet.getFieldAndAlias());
            // 设置只导出有别名的字段
            bigWriter.setOnlyAlias(true);
            // 设置默认行高
            bigWriter.setDefaultRowHeight(18);
            // 设置冻结行
            bigWriter.setFreezePane(1);
            // 一次性写出内容,使用默认样式,强制输出标题
            bigWriter.write(sheet.getCollection(), true);
            // 设置所有列为自动宽度,不考虑合并单元格
//            bigWriter.autoSizeColumnAll();
        }
        
        ServletOutputStream out = null;
        try {
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", 
                    "attachment;filename=" + 
                            URLEncoder.encode(fileName + DateUtil.today() + ".xlsx", "UTF-8"));
            out = response.getOutputStream();
            bigWriter.flush(out, true);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭writer,释放内存
            bigWriter.close();
        }
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}

/**
 * Excel - Sheet页
 */
public class SheetDTO implements Serializable {

    private static final long serialVersionUID = 1L;
    
    /** sheet页名称 */
    private String sheetName;
    
    /** 
     * 字段和别名,如果使用这个,properties 和 titles可以不用处理 
     * Map<字段, 别名>  如:Map<"name", "姓名">
     */
    private Map<String, String> fieldAndAlias;
    
    /**
     * 列宽<br/>
     * 设置列宽时必须每个字段都设置才生效(columnWidth.size = fieldAndAlias.size)
     */
    private List<Integer> columnWidth;
    
    /** 数据集 */
    private Collection<?> collection; 
    
    public SheetDTO() {
        
    }
    
    /**
     * 
     * @param sheetName      sheet页名称
     * @param fieldAndAlias  字段和别名
     * @param collection     数据集
     */
    public SheetDTO(String sheetName, Map<String, String> fieldAndAlias, Collection<?> collection) {
        super();
        this.sheetName = sheetName;
        this.fieldAndAlias = fieldAndAlias;
        this.collection = collection;
    }

    public String getSheetName() {
        return sheetName;
    }

    public void setSheetName(String sheetName) {
        this.sheetName = sheetName;
    }

    public Map<String, String> getFieldAndAlias() {
        return fieldAndAlias;
    }

    public void setFieldAndAlias(Map<String, String> fieldAndAlias) {
        this.fieldAndAlias = fieldAndAlias;
    }

    public List<Integer> getColumnWidth() {
        return this.columnWidth;
    }

    public void setColumnWidth(List<Integer> columnWidth) {
        this.columnWidth = columnWidth;
    }

    public Collection<?> getCollection() {
        return collection;
    }

    public void setCollection(Collection<?> collection) {
        this.collection = collection;
    }

}

// 示例Controller
public Class TestController {

    /**
     * 条件全部导出
     */
    @ResponseBody
    @RequestMapping("/export_all")
    public void export_all(HttpServletResponse response) { 
        List<Map<String, Object>> listData1 = xxxService.listData1();
        List<Map<String, Object>> listData2 = xxxService.listData2();
        List<Map<String, Object>> listData3 = xxxService.listData3();

		Map<String, String> map1 = new LinkedHashMap<String, String>();
		map1.put("store_name", "客户名称");
		map1.put("store_out_trade_no", "客户编码");
		map1.put("store_contract_year", "年份");
		map1.put("business_dept_name", "所属事业部");
		
		Map<String, String> map2 = new LinkedHashMap<String, String>();
		map2.put("store_name", "客户名称");
		map2.put("store_out_trade_out", "客户编码");
		map2.put("store_contract_year", "年份");
		map2.put("store_name", "关联客户名称");
		map2.put("store_out_trade_out", "关联客户编码");
		
		Map<String, String> map3 = new LinkedHashMap<String, String>();
		map3.put("store_name", "客户名称");
		map3.put("store_out_trade_out", "客户编码");
		map3.put("store_contract_year", "年份");
		map3.put("name", "重要负责人姓名");
		map3.put("position", "重要负责人职位");

		List<SheetDTO> arrayList = new ArrayList<SheetDTO> ();
    	arrayList.add(new SheetDTO("客户信息", map1, listData1));
        arrayList.add(new SheetDTO("关联客户信息", map2, listData2));
        arrayList.add(new SheetDTO("重要负责人信息", map3, listData3));

        HuExcelUtils.exportExcel(response, arrayList, "客户信息导出");
    }

}

java解决poi导出excel使用SXSSF时“Attempting to write a row[?] in the range [0,?]that is already written to disk.”异常

package com.***;

import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.bison.tracecode.vo.WineMonthExcelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/***
 * 导入
 * @author: ***
 * @date 2021/9/17 17:00
 **/

@Slf4j
public class ExcelExportUtil {

	public static void setSizeColumn(Sheet sheet, int size) {
		for (int columnNum = 0; columnNum <= size; columnNum++) {
			int columnWidth = sheet.getColumnWidth(columnNum) / 256;
			for (int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
				Row currentRow;
				//当前行未被使用过
				if (sheet.getRow(rowNum) == null) {
					currentRow = sheet.createRow(rowNum);
				} else {
					currentRow = sheet.getRow(rowNum);
				}

				if (currentRow.getCell(columnNum) != null) {
					Cell currentCell = currentRow.getCell(columnNum);
					int cellType = currentCell.getCellType();
					int code = CellType.STRING.getCode();
					if (cellType == code) {
						int length = currentCell.getStringCellValue().getBytes().length;
						if (columnWidth < length) {
							columnWidth = length;
						}
					}
				}
			}
			sheet.setColumnWidth(columnNum, columnWidth * 256);
		}
	}



	/**
	 * 导出多个 Sheet 页
	 * @param response
	 * @param sheetList 页数据
	 * @param fileName 文件名
	 */
	public static void exportExcel(HttpServletResponse response, List<WineMonthExcelVO> sheetList, String fileName) {
		ExcelWriter bigWriter = ExcelUtil.getWriter();
		// 重命名第一个Sheet的名称,不然会默认多出一个Sheet1的页
		bigWriter.renameSheet(0, sheetList.get(0).getSheetName());
		for (WineMonthExcelVO sheet : sheetList) {
			// 指定要写出的 Sheet 页
			bigWriter.setSheet(sheet.getSheetName());
			// 设置字段和别名
			bigWriter.setHeaderAlias(sheet.getFieldAndAlias());
			// 设置只导出有别名的字段
			bigWriter.setOnlyAlias(true);
//			// 设置默认行高
//			bigWriter.setDefaultRowHeight(18);
			// 设置冻结行
			bigWriter.setFreezePane(1);
			// 一次性写出内容,使用默认样式,强制输出标题
			bigWriter.write(sheet.getCollection(), true);
			// 设置所有列为自动宽度,不考虑合并单元格
			setSizeColumn(bigWriter.getSheet(), sheet.getCollection().size());
//            bigWriter.autoSizeColumnAll();
		}

		ServletOutputStream out = null;
		try {
			//response为HttpServletResponse对象
			response.setContentType("application/vnd.ms-excel;charset=utf-8");
			response.setHeader("Content-Disposition",
				"attachment;filename=" +
					URLEncoder.encode(fileName + ".xlsx", "UTF-8"));
			out = response.getOutputStream();
			bigWriter.flush(out, true);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭writer,释放内存
			bigWriter.close();
		}
		//此处记得关闭输出Servlet流
		IoUtil.close(out);
	}


}

posted on   何苦->  阅读(1212)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示