java使用POI来导出List数据类型集合的Excel

**

Java中使用POI来导出List数据类型集合的Excel

**

第一步,无非导项目所需要包


    org.apache.poi
    poi
    3.17


    org.apache.poi
    poi-ooxml
    3.17

第二部使用工具类

  package com.srhub.util;

/**
 * @author: zj
 * Created by 2019 08 27
 * @description:
 */
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
//这里所需要的参数是  表格文件名  表格的sheet的名称   与表格的头部内容 和数据集合,以及response
public class ExportExcel
{
    public static boolean exportExcel(String excelName, String title, String[] headers, List dataset, String pattern, HttpServletResponse response) throws IOException {

        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String fileName = excelName + "-" + milliSecond + ".xls";
            ServletOutputStream outputStream = response.getOutputStream();
        response.setContentType("application/x-xls;charset=UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);

        boolean flag = false;
        Workbook workbook = null;
        if (fileName.endsWith("xlsx"))
        {
            workbook = new XSSFWorkbook();
        } else if (fileName.endsWith("xls"))
        {
            workbook = new HSSFWorkbook();
        } else
        {
            try
            {
                throw new Exception("invalid file name, should be xls or xlsx");
            } catch (Exception e)
            {
                e.printStackTrace();
            }

        }

        Sheet sheet = workbook.createSheet(title);
        CellStyle style = workbook.createCellStyle();

        // 列名
        Row row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++)
        {
            Cell cell = row.createCell(i);
            sheet.setColumnWidth(i, 5000);
//            style.setAlignment(CellStyle.ALIGN_CENTER);
            cell.setCellValue(headers[i]);
        }

        Iterator it = dataset.iterator();
        int index = 0;
        while (it.hasNext())
        {
            index++;
            row = sheet.createRow(index);

            Map map = it.next();
//            logger.info(map.toString());
            Set mapKey = (Set)map.keySet();
//            logger.info(mapKey.toString());
            Iterator iterator = mapKey.iterator();
//            logger.info(iterator.toString());
            int num  = 0;
            while(iterator.hasNext()){
                Cell cell = row.createCell(num);
                num++;
                String key = iterator.next();
//                logger.info(key);
                Object obj = map.get(key);
                if (obj instanceof Date)
                {
                    SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                    cell.setCellValue(sdf.format(obj));
                } else if (obj instanceof Integer)
                {
                    cell.setCellValue((Integer) obj);
                } else if (obj instanceof Double)
                {
                    cell.setCellValue((Double) obj);
                } else
                {
                    cell.setCellValue((String) obj);
                }
            }
        }
        FileOutputStream fos;
        try
        {
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            flag = true;
        } catch (FileNotFoundException e)
        {
//            logger.info("文件不存在");
            flag = false;
            e.printStackTrace();
        } catch (IOException e)
        {
//            logger.info("文件写入错误");
            flag = false;
            e.printStackTrace();

        }
        return flag;
    }
}

在控制层引用

   public ResultModal queryAll2(HttpServletRequest request, HttpServletResponse response) throws IOException {
   //查询出你所需要的数据类型是List
        List list = orderService.queryAll();

        System.out.println(list);
        //表格的头部标签,与你查出来的数据对应即可
        String[] columnNames = { "详细地址","购买时间", "商品规格","用户名", "收货人姓名", "订单号", "收货区域", "购买商品", "购买数量" ,"" ,"订单状态","收货人手机号","订单金额","提交时间","发货状态","支付方式"};

       ExportExcel.exportExcel("商城订单表","商城订单表",columnNames,list,"yyyy-MM-dd HH:mm:ss",response);
        return null;
    }

然后直接在浏览器数量接口的地址可直接下载
java使用POI来导出List数据类型集合的Excel_第1张图片

你可能感兴趣的:(工作中所遇到的)