欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java 导入、导出Excel

程序员文章站 2024-02-24 13:40:25
...

java导入Excel数据

Controller层

 @PostMapping(value = "/importInfo")
    public Map<String, Object> importInfo(@CookieValue(value = "token_back") String token, @RequestParam(value = "file") MultipartFile file, @RequestParam(value = "code") String code) {
        TbSysUser user = RedisUtil.tokenToUser(token);
        //操作人员代码
        String operatorId = user.getLoginCode();
        //操作人员姓名
        String operatorName = user.getName();
        // 操作时间
        Timestamp operateDateTime = new Timestamp(new Date().getTime());
        Map<String, Object> map = new HashMap<>();
        try {
            String message = memberImportService.exportInfo(file, code, operatorId, operatorName, operateDateTime);
            map.put("success", true);
            map.put("message", message);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("success", false);
            map.put("message", "导入失败");
            return map;
        }
    }

ServiceImpl层

@Override
    public String exportInfo(MultipartFile file, String code, String operatorId, String operatorName, Timestamp operateDateTime) throws Exception {
        String message = "导入成功";
        String listTypeID = code.split("\\*")[0].toString().trim();
        String listTypeName = code.split("\\*")[1].toString().trim();
        Workbook workbook = null;
        String fileName = file.getOriginalFilename();
        ExcelUtil eu = new ExcelUtil();
        //判断文件类型
        if (fileName.endsWith("xls")) {
            try {
                workbook = new HSSFWorkbook(file.getInputStream());// 2003版本
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if (fileName.endsWith("xlsx")) {
            try {
                workbook = new XSSFWorkbook(file.getInputStream());// 2007版本
            } catch (IOException e) {
                e.printStackTrace();
            }

        } else {
            try {
                throw new Exception("文件不是Excel文件");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Sheet sheet = workbook.getSheet("sheet1");
        int rows = sheet.getLastRowNum();
        if (rows == 0) {
            try {
                throw new Exception("数据为空请重新填写数据");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //获取Excel文档中的第一个表单
        Sheet sht0 = workbook.getSheetAt(0);
        Row ro = sht0.getRow(1);
        boolean flag = false;
        Cell cell = ro.getCell(4);
        String cellName = null;
        if (cell != null) {
            cellName = cell.getStringCellValue();
        }
        if (cellName != null && cellName.trim().length() > 0) {
            if (!"备注".equals(cellName)) {
                message = "导入模板错误,请重新导入";
                return message;
            }
            flag = true;
        } else {
            cell = ro.getCell(2);
            if (cell != null) {
                cellName = cell.getStringCellValue();
            }

            if (cellName == null || (cellName.trim().length() > 0 && !"备注".equals(cellName))) {
                message = "导入模板错误,请重新导入";
                return message;
            }
        }
        //对Sheet中的每一行进行迭代
        for (Row r : sht0) {
            //如果当前行的行号(从0开始)未达到2(第三行)则从新循环
            int rnum = r.getRowNum() + 1;
            if (r.getRowNum() < 2) {
                continue;
            }
            //创建实体类
            TbMemberImport info = new TbMemberImport();
            //取出当前行第1个单元格数据,并封装在info实体stuName属性上
            //年份
            info.setYear(eu.getCellValue(r.getCell(0)));
            //交易商名称
            info.setFullName(eu.getCellValue(r.getCell(1)));
            if (flag) {
                //品种
                String memo = eu.getCellValue(r.getCell(4));
                if (memo != null && memo.trim().length() > 0) {
                    //备注
                    info.setMemo(eu.getCellValue(r.getCell(4)));
                } else {
                    message = "第" + rnum + "行备注不能为空!";
                    return message;
                }
                info.setVarietyName(eu.getCellValue(r.getCell(2)));
                //日处理能力
                info.setDayProcess(new java.math.BigDecimal(eu.getCellValue(r.getCell(3))));
            } else {
                //备注
                String memo = eu.getCellValue(r.getCell(2));
                if (memo != null && memo.trim().length() > 0) {
                    //备注
                    info.setMemo(eu.getCellValue(r.getCell(4)));
                } else {
                    message = "第" + rnum + "行备注不能为空!";
                    return message;
                }
            }
            info.setMemberId("");
            info.setVarietyId("");
            info.setOperatorId(operatorId);
            info.setOperatorName(operatorName);
            info.setOperateDateTime(operateDateTime);
            info.setListTypeId(listTypeID);
            info.setListTypeName(listTypeName);
            info.setStatus("WX");
            tbMemberImportMapper.insert(info);
            for (int i = 1; i <= rows + 1; i++) {
                Row row = sheet.getRow(i);
                if (row != null) {

                }
            }
        }
        return message;
    }

java 导出Excel

Controller层

 @PostMapping("/export")
    public void exportContractList(HttpServletRequest request, HttpServletResponse response, @CookieValue(value="token_back")String token){
        try {
            List<TbContractExport> contractList = contractMngService.contractExportData(request,RedisUtil.tokenToUser(token));

            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+"合同信息", "UTF-8") + ".xls");
            ExcelUtil<TbContractExport> excelUtil = new ExcelUtil<>();
            excelUtil.exportExcel2003("合同信息", exportColumns, contractList, response.getOutputStream(), "yyyy-MM-dd");
        }catch (Exception e){
            //暂不处理,后期发送消息到rabbitMQ写入日志表
        }
    }
 @GetMapping(value = "/exportExcel")
    public void exportExcel(
            HttpServletResponse response,
            @RequestParam(value = "data") String data
    ) {
        try {
            JSONObject jsonObject = JSONObject.parseObject(data);
            String buyStatus = jsonObject.getString("buyStaus");
            String fullName = jsonObject.getString("fullName");
            String listTypeId = jsonObject.getString("listTypeId");
            String marketId = jsonObject.getString("marketId");
            String marketIdZc = jsonObject.getString("marketIdZc");
            String memberId = jsonObject.getString("memberId");
            String varietyId = jsonObject.getString("varietyId");
            String status = jsonObject.getString("status");
            String specialNo = jsonObject.getString("specialNo");
//            OutputStream os = response.getOutputStream();
            memberBuyNumLimitService.exportExcel(response, buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

ServiceImpl层

 @Override
    public void exportExcel(HttpServletResponse response, String buyStatus, String fullName, String listTypeId, String marketId, String marketIdZc, String memberId, String varietyId, String status, String specialNo) throws Exception {
//        List<TbMemberBuyNumLimitView> list = tbMemberBuyNumLimitMapper.getMemberBuyInfo(buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        List<TbMemberBuyNumLimitView> list = null;
        if (marketIdZc == null || marketIdZc.trim().length() <= 0) {
            list = tbMemberBuyNumLimitMapper.getMemberBuyInfo(buyStatus, fullName, listTypeId, marketId, memberId, varietyId, status, specialNo);
        } else {
            list = tbMemberBuyNumLimitMapper.getMemberBuyInfoZc(buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
        }

        ExcelUtil excelUtil = new ExcelUtil();
        String[] headers = {"名单", "代码", "名称", "市场", "专场", "品种", "处理能力", "单次可交易量", "1可交易量", "2可交易量", "承诺书", "交易状态", "交易量限制"};
        List<Object> rows = new ArrayList<>();
        for (TbMemberBuyNumLimitView tb : list) {
            List<String> row = new ArrayList<>();
            String numConvertName = tb.getNumConvertName();
            row.add(tb.getListTypeName());
            row.add(tb.getMemberId());
            row.add(tb.getFullName());
            row.add(tb.getMarketName());
            row.add(tb.getSpecialName());
            row.add(tb.getVarietyName());
            if(tb.getDayProcess() == null){
                row.add("无数据");
            }else{
                row.add(tb.getDayProcess().toString() + numConvertName);
            }
            if(tb.getSingleBuy() == null){
                row.add("无数据");
            }else {
                row.add(tb.getSingleBuy().toString() + numConvertName);
            }
            if(tb.getMonthBuy() == null){
                row.add("无数据");
            }else {
                row.add(tb.getMonthBuy().toString() + numConvertName);
            }
            if(tb.getTotalBuy() == null){
                row.add("无数据");
            }else {
                row.add(tb.getTotalBuy().toString() + numConvertName);
            }
            String commitment = tb.getCommitment();
            if ("Y".equals(commitment)) {
                row.add("是");
            } else {
                row.add("否");
            }
            String bs = tb.getBuyStatus();
            if ("Y".equals(bs)) {
                row.add("可交易");
            } else {
                row.add("停止交易");
            }
            String st = tb.getStatus();
            if ("Y".equals(st)) {
                row.add("限制");
            } else {
                row.add("不限制");
            }
            rows.add(row);
        }
        String time = DateUtils.dateToStringByTemplate(new Date(), "yyyyMMddHHmmss");
        String fileName = time + "*****列表.xls";
        excelUtil.listToExcel(headers, rows, fileName, "某某列表", response);
    }

导出Excel工具


import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 
 * @description Excel导入导出工具类
 * @date 2018-8-2
 */
public class ExcelUtil<T> {
    // 2007 版本以上 最大支持1048576行
    public final static String EXCEL_FILE_2007 = "2007";
    // 2003 版本 最大支持65536 行
    public final static String EXCEL_FILE_2003 = "2003";

    /**
     * 功能描述 导出无头部标题行Excel
     *
     * @param title   表格sheet标题
     * @param dataset 数据集合
     * @param out     输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     * @return void
     * @author 
     * @date 2018-8-2
     */
    public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
        if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
        } else {
            exportExcel2007(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
        }
    }

    /**
     * 功能描述 导出带有头部标题行的Excel
     *
     * @param title   表格sheet标题
     * @param headers 头部标题集合
     * @param dataset 数据集合
     * @param out     输出流
     * @param version 2003 或者 2007,不传时默认生成2003版本
     * @return void
     * @author 
     * @date 2018-8-2
     */
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String version) {
        if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
            exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
        } else {
            exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
        }
    }

    /**
     * 功能描述
     * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中
     * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
     *
     * @param title   表格sheet标题名
     * @param headers 表格头部标题集合
     * @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *                JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out     与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     * @return void
     * @author 
     * @date 2018-8-2
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
        // 声明一个工作薄
        XSSFWorkbook workbook = new XSSFWorkbook();
        // 生成一个表格
        XSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        XSSFCellStyle style = workbook.createCellStyle();

        // 设置这些样式(表头)
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setFillForegroundColor(new XSSFColor(Color.GRAY));
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一个字体
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setColor(new XSSFColor(Color.BLACK));
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 生成并设置另一个样式(内容)
        XSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setFillForegroundColor(new XSSFColor(Color.WHITE));
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成另一个字体
        XSSFFont font2 = workbook.createFont();
        font2.setBold(false);
        font2.setFontName("宋体");
        font2.setColor(new XSSFColor(Color.BLACK));
        font2.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 产生表格标题行
        XSSFRow row = sheet.createRow(0);
        XSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T t;
        Field[] fields;
        Field field;
        XSSFRichTextString richString;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        Matcher matcher;
        String fieldName;
        String getMethodName;
        XSSFCell cell;
        Class tCls;
        Method getMethod;
        Object value;
        String textValue;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
            //如果实体类里有serialVersionUID,请将serialVersionUID放在所有属性之后声明,否则会出现第一列为空
            fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                field = fields[i];
                fieldName = field.getName();
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new XSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }
            }
        }
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
     * 此方法生成2003版本的excel,文件名后缀:xls
     *
     * @param title   表格sheet标题名
     * @param headers 表格头部标题集合
     * @param dataset 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
     *                JavaBean属性的数据类型有基本数据类型及String,Date
     * @param out     与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
     * @param pattern 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
     * @return void
     * @author 
     * @date 2018-8-2
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet(title);
        // 设置表格默认列宽度为15个字节
        sheet.setDefaultColumnWidth(20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_50_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontName("宋体");
        font.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        font.setFontHeightInPoints((short) 11);
        // 把字体应用到当前的样式
        style.setFont(font);
        // 生成并设置另一个样式
        HSSFCellStyle style2 = workbook.createCellStyle();
        style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
        style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        // 生成另一个字体
        HSSFFont font2 = workbook.createFont();
        font2.setBold(false);
        // 把字体应用到当前的样式
        style2.setFont(font2);

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        HSSFCell cellHeader;
        for (int i = 0; i < headers.length; i++) {
            cellHeader = row.createCell(i);
            cellHeader.setCellStyle(style);
            cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
        }

        // 遍历集合数据,产生数据行
        Iterator<T> it = dataset.iterator();
        int index = 0;
        T t;
        Field[] fields;
        Field field;
        HSSFRichTextString richString;
        Pattern p = Pattern.compile("^//d+(//.//d+)?$");
        Matcher matcher;
        String fieldName;
        String getMethodName;
        HSSFCell cell;
        Class tCls;
        Method getMethod;
        Object value;
        String textValue;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            t = (T) it.next();
            // 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
            //如果实体类里有serialVersionUID,请将serialVersionUID放在所有属性之后声明,否则会出现第一列为空
            fields = t.getClass().getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                field = fields[i];
                fieldName = field.getName();
                if ("serialVersionUID".equals(fieldName)) {
                    continue;
                }
                cell = row.createCell(i);
                cell.setCellStyle(style2);
                getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
                        + fieldName.substring(1);
                try {
                    tCls = t.getClass();
                    getMethod = tCls.getMethod(getMethodName, new Class[]{});
                    value = getMethod.invoke(t, new Object[]{});
                    // 判断值的类型后进行强制类型转换
                    textValue = null;
                    if (value instanceof Integer) {
                        cell.setCellValue((Integer) value);
                    } else if (value instanceof Float) {
                        textValue = String.valueOf((Float) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Double) {
                        textValue = String.valueOf((Double) value);
                        cell.setCellValue(textValue);
                    } else if (value instanceof Long) {
                        cell.setCellValue((Long) value);
                    }
                    if (value instanceof Boolean) {
                        textValue = "是";
                        if (!(Boolean) value) {
                            textValue = "否";
                        }
                    } else if (value instanceof Date) {
                        textValue = sdf.format((Date) value);
                    } else {
                        // 其它数据类型都当作字符串简单处理
                        if (value != null) {
                            textValue = value.toString();
                        }
                    }
                    if (textValue != null) {
                        matcher = p.matcher(textValue);
                        if (matcher.matches()) {
                            // 是数字当作double处理
                            cell.setCellValue(Double.parseDouble(textValue));
                        } else {
                            richString = new HSSFRichTextString(textValue);
                            cell.setCellValue(richString);
                        }
                    }
                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                } finally {
                    // 清理资源
                }
            }
        }
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导出Excel
     *
     * @param titles    数据头
     * @param valueList 数据体
     * @param fileName  Excel文件名
     * @param sheetName 首个sheet页名
     * @param response
     */
    public void listToExcel(String[] titles, List<List<Object>> valueList, String fileName, String sheetName, HttpServletResponse response) {
        try {
            response.setContentType("application/x-download");
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.addHeader("Content-Disposition", "attachement;filename=" + fileName);
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            HSSFDataFormat format = workbook.createDataFormat();
            HSSFSheet sheet = workbook.createSheet();
            if (sheetName != null && sheetName.trim().length() >0 ) {
                workbook.setSheetName(0, sheetName);
            }
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell;
            Set<String> set = new HashSet<>();
            // 构建表头
            for (int i = 0; i < titles.length; i++) {
                String title = titles[i];
//                cell = row.createCell[i];
                cell = row.createCell(i);
                cell.setCellType(CellType.STRING);
                cell.setCellValue(title);
            }
            // 构建表格
            for (int j = 0; j < valueList.size(); j++) {
                List<Object> values = valueList.get(j);
                row = sheet.createRow(j + 1);
                for (int m = 0; m < values.size(); m++) {
                    cell = row.createCell(m);
                    cell.setCellType(CellType.STRING);
                    if (values.get(m) != null) {
                        cell.setCellValue(values.get(m).toString());
                    } else {
                        cell.setCellValue("");
                    }
                }
            }
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Excel单元格的值
     *
     * @param cell
     * @return
     */
    public String getCellValue(Cell cell) {
        String value = "";
        if (cell != null) {
            switch (cell.getCellTypeEnum()) {
                case NUMERIC:  //数字
                    value = cell.getNumericCellValue() + "";
                    if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd").format(date);//日期格式化
                        } else {
                            value = "";
                        }
                    } else {
                        //在解析cell的时候,数字类型默认是double的,但是想要的的整数的类型,需要格式化,很重要
                        value = new DecimalFormat("0").format(cell.getNumericCellValue());
                    }
                    break;
                case STRING://字符串
                    value = cell.getStringCellValue();
                    break;
                case BOOLEAN://boolean类型
                    value = cell.getBooleanCellValue() + "";
                    break;
                case BLANK://空值
                    value = "";
                    break;
                case ERROR://错误类型
                    value = "非法字符";
                    break;
                default:
                    value = "未知类型";
            }
        }
        return value.trim();
    }


}

相关标签: java excel