POI Excel 通用工具类 导出

这是Controller里的代码

import java.io.IOException;

import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import java.util.List;
import java.util.Map;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


import com.fty.entity.Merch;

import com.fty.service.MerchServiceImpl;

import com.fty.util.ExportExcelkit;
import com.fty.util.InputExcelUtil;
import com.fty.util.UtilId;


import org.springframework.util.CollectionUtils;





@RequestMapping(value="/exports.action")
    public void export(HttpServletResponse response) throws IOException{
    	Map<String, String> title = new HashMap<>();    // 表头
        List<Map<String, Object>> data = new ArrayList<>();     // 需要导出的数据
        Map<String, Integer> position = new HashMap<>();        // 表头字段对应的位置(自定义位置)
     // 设置表头字段位置
        position.put("code", 0);
        position.put("name", 1);
        position.put("factory", 2);
        position.put("package", 3);
        position.put("price", 4);
        // 设置表头信息
        title.put("code", "编号");
        title.put("name", "名称");
        title.put("factory", "厂商");
        title.put("package", "包装类型");
        title.put("price", "价格");
     // 遍历模拟的数据填充到userMap集合
        List<Merch> ad=ssi.getMerchGetAll();
        System.out.println(ad);
        Map<String, Object> userMap = null;
        
        for (Merch adc : ad) {
            userMap = new HashMap<>();
            userMap.put("code",adc.getCode());
            userMap.put("name", adc.getName());
            userMap.put("factory", adc.getFactory());
            userMap.put("package", adc.getPackage());
            userMap.put("price", adc.getPrice());
            data.add(userMap);     // 将userMap添加到List集合中
            System.out.println(userMap);
        }
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = df.format(new Date());
        String excelName = "商品列表" + date + ".xlsx";
        String sheetName = "商品列表数据";
        excelName = URLEncoder.encode(excelName, "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + excelName);
        response.setContentType("application/x-download");
        // 调用写好的工具类的导出数据方法   传入对应的参数
        ExportExcelkit.exportDataToExcel(title, position, data, sheetName, response.getOutputStream());

    }

这是POI工具类的代码

package com.fty.util;

import org.apache.poi.ss.usermodel.*;


import org.apache.poi.xssf.usermodel.XSSFFont;


import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.IOException;


import java.io.OutputStream;


import java.util.List;


import java.util.Map;


/**
 * 导出Excel工具包
 * 通用类
 * 需要Map<String, String> title, Map<String, Integer> position, List<Map<String, Object>> data,
 * String sheetName, OutputStream outputStream
 * title: 表格列头
 * position: 表头列的位置
 * data: 数据集合,对象数据需要转为Map<k, v>
 * sheetName: 出数据后在excel表格中左下角显示的工作簿名称(注意:不是导出后的文件名)
 * outputStream: 输出流,通常在controller层以response.getOutputStream的形式获取
 * 三个Map集合key值保持一致
 * @author HongYang
 * @since 2018/4/26
 */

public class ExportExcelkit {

	
 
	
 
    /**
     * 导出列表数据
     * @param title 表头集合
     * @param position  表头字段位置集合
     * @param data 需要导出的数据
     * @param sheetName 导出数据后在excel表格中左下角显示的工作簿名称(注意:不是导出后的文件名)
     * @param outputStream 从controller层通过response获取到的输出流
     * @throws IOException
     * @throws ExcelExportException
     */
    public static void exportDataToExcel(Map<String, String> title, Map<String, Integer> position, List<Map<String, Object>> data, String sheetName, OutputStream outputStream) throws IOException {
        if (data == null || data.size() < 1) {
            return;
        }
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);
            Row header = sheet.createRow(0);
            // 设置表头样式
            CellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            // 字体样式
            XSSFFont font = ((XSSFWorkbook) workbook).createFont();
            font.setFontName("Arial");
            font.setFontHeightInPoints((short)14);
            headerStyle.setFont(font);
            int col = 0;
            // 遍历表头map集合
            for (String key: title.keySet()) {
                sheet.setColumnWidth(col, 6000);
                // 设置表格头部
                Cell headerCell = header.createCell(position.get(key));
                headerCell.setCellValue(title.get(key) + "");
                headerCell.setCellStyle(headerStyle);
                col++;
            }
            CellStyle style = workbook.createCellStyle();
            style.setWrapText(true);
            /*
             * 遍历要导出列表的数据data 并与title的key相比较, 确认后插入值
             * 创建列时,根据title的key然后将值插入到对应的列中(position,dataMap,title三个集合的key值是一一对应的)
             */
            if (data != null && data.size() > 0) {
                int r = 0;
                for (Map<String, Object> dataMap : data) {
                    Row row = sheet.createRow(r + 1);
                    for (String dkey : dataMap.keySet()) {
                        for (String key : title.keySet()) {
                            if (key.equals(dkey)) {
                                Cell cell = row.createCell(position.get(key));
                                cell.setCellValue(dataMap.get(dkey) + "");
                                cell.setCellStyle(style);
                                break;
                            }
                        }
                    }
                    r++;
                }
            }
            workbook.write(outputStream);
        } catch (Exception ex) {
           
        }
    }

	
	
}

第一次写没什么经验不喜勿喷
可以留个邮箱我给你发源码 或者加我QQ1052678420也能发

发布了40 篇原创文章 · 获赞 53 · 访问量 7723

猜你喜欢

转载自blog.csdn.net/qq_44758351/article/details/104177161