excel导出

根据一个博主的方法改的,原代码是传一个对象,自己改成了一个List<Map<String,Object>>的形式(只改了生成xls 2003的版本)

 package cn.htd.erp.cppt.common;
 
import java.io.OutputStream;
import java.text.DateFormat;
import java.util.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
     * 导出Excel
     *
     * @param <T>
     */
    public class CPPTExportExcelUtil<T>{

        // 2007 版本以上 最大支持1048576行
        public  final static String  EXCEl_FILE_2007 = "2007";
        // 2003 版本 最大支持65536 行
        public  final static String  EXCEL_FILE_2003 = "2003";

        /**
         * <p>
         * 导出带有头部标题行的Excel <br>
         * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
         * </p>
         *
         * @param title 表格标题
         * @param headers 头部标题集合
         * @param list 数据集合
         * @param out 输出流
         * @param version 2003 或者 2007,不传时默认生成2003版本
         */
        public void exportExcel(String title,String[] headers, List<Map<String,Object>> list, OutputStream out,String version,String s) {
            if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
                exportExcel2003(title, headers, list, out,s);
            }else{
           //     exportExcel2007(title, headers, list, out, "yyyy-MM-dd HH:mm:ss");
            }
        }

        /**
         * <p>
         * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
         * 此版本生成2007以上版本的文件 (文件后缀:xlsx)
         * </p>
         *
         * @param title
         *            表格标题名
         * @param headers
         *            表格头部标题集合
         * @param dataset
         *            需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
         *            JavaBean属性的数据类型有基本数据类型及String,Date
         * @param out
         *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
         * @param pattern
         *            如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
         */
        @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);
            // 设置表格默认列宽度为15个字节
            sheet.setDefaultColumnWidth(20);
            // 生成一个样式
            XSSFCellStyle style = workbook.createCellStyle();
            // 设置这些样式
            style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
            style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
            style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            style.setBorderRight(XSSFCellStyle.BORDER_THIN);
            style.setBorderTop(XSSFCellStyle.BORDER_THIN);
            style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            // 生成一个字体
            XSSFFont font = workbook.createFont();
            font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
            font.setFontName("宋体");
            font.setColor(new XSSFColor(java.awt.Color.BLACK));
            font.setFontHeightInPoints((short) 11);
            // 把字体应用到当前的样式
            style.setFont(font);
            // 生成并设置另一个样式
            XSSFCellStyle style2 = workbook.createCellStyle();
            style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
            style2.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
            style2.setBorderBottom(XSSFCellStyle.BORDER_THIN);
            style2.setBorderLeft(XSSFCellStyle.BORDER_THIN);
            style2.setBorderRight(XSSFCellStyle.BORDER_THIN);
            style2.setBorderTop(XSSFCellStyle.BORDER_THIN);
            style2.setAlignment(XSSFCellStyle.ALIGN_CENTER);
            style2.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
            // 生成另一个字体
            XSSFFont font2 = workbook.createFont();
            font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
            // 把字体应用到当前的样式
            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()方法得到属性值
                fields = t.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    cell = row.createCell(i);
                    cell.setCellStyle(style2);
                    field = fields[i];
                    fieldName = field.getName();
                    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 (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();
            }
        }



        /**
         * <p>
         * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br>
         * 此方法生成2003版本的excel,文件名后缀:xls <br>
         * </p>
         *
         * @param title
         *            表格标题名
         * @param headers
         *            表格头部标题集合
         * @param list
         *
         * @param out
         *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public void exportExcel2003(String title, String[] headers, List<Map<String,Object>> list, OutputStream out,String s) {
            // 声明一个工作薄
            HSSFWorkbook workbook = new HSSFWorkbook();
            // 生成一个表格
            HSSFSheet sheet = workbook.createSheet(title);

            //生成一个样式
            HSSFCellStyle headerStyle = workbook.createCellStyle();
            headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中       
            headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
            //生成一个字体
            HSSFFont headerFont = workbook.createFont();
            headerFont.setFontName("黑体");
            headerFont.setFontHeightInPoints((short) 12);
            headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
            headerStyle.setFont(headerFont);

            //生成其他样式
            HSSFCellStyle otherStyle = workbook.createCellStyle();
            HSSFFont otherFont = workbook.createFont();
            otherFont.setFontName("宋体");
            otherFont.setFontHeightInPoints((short) 10);
            otherFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
            otherStyle.setFont(otherFont);

            //生成单元格样式
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
            cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//下边框       
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框       
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框       
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框
            HSSFFont cellFont = workbook.createFont();
            cellFont.setFontName("宋体");
            cellFont.setFontHeightInPoints((short) 10);
            cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
            cellStyle.setFont(cellFont);

            //创建合并单元格对象
            sheet.addMergedRegion(new CellRangeAddress(0,1,0,5));//起始行,结束行,起始列,结束列

            // 产生表格标题行
            HSSFRow headerRow = sheet.createRow(0);
            HSSFCell headerCell = headerRow.createCell(0);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
            String date = df.format(new Date());
            String row1 = s+"现场盘点表("+date+")";
            headerCell.setCellStyle(headerStyle);
            headerCell.setCellValue(row1);

            //单位行
            HSSFRow otherRow = sheet.createRow(2);
            HSSFCell otherCell = otherRow.createCell(3);
            otherCell.setCellStyle(otherStyle);
            otherCell.setCellValue("(单位:元,台/件等)");

            //表格插入
            HSSFRow cellRow = sheet.createRow(3);
            HSSFCell cellHeader;
            for (int i = 0; i < headers.length; i++) {
                cellHeader = cellRow.createCell(i);
                cellHeader.setCellStyle(cellStyle);
                cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
            }

            int index = 3;
            HSSFRow dataseRow;
            HSSFCell dataseCell;

                for (int i = 0; i < list.size(); i++) {
                    index++;
                    dataseRow = sheet.createRow(index);
                    for (int j = 0;j<headers.length;j++){
                        dataseCell = dataseRow.createCell(j);
                        dataseCell.setCellStyle(cellStyle);
                        String value = String.valueOf(list.get(i).get(headers[j]) == null ? " " : String.valueOf(list.get(i).get(headers[j])));
                        dataseCell.setCellValue(value);//缺少类型转换
                    }
                }
            //end
            index++;
            //创建合并单元格对象
   //         sheet.addMergedRegion(new CellRangeAddress(index,index,0,5));//起始行,结束行,起始列,结束列

            HSSFRow endRow = sheet.createRow(index);
            HSSFCell endCell = endRow.createCell(0);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue("数量合计:");
            endCell = endRow.createCell(1);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue(" ");
            endCell = endRow.createCell(2);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue(" ");
            endCell = endRow.createCell(3);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue(" ");
            endCell = endRow.createCell(4);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue(" ");
            endCell = endRow.createCell(5);
            endCell.setCellStyle(cellStyle);
            endCell.setCellValue(" ");


            //endend
            index++;
            index++;
            HSSFRow lastRow = sheet.createRow(index);
            HSSFCell lastCell = lastRow.createCell(0);
            lastCell.setCellStyle(otherStyle);
            lastCell.setCellValue("盘点人:");
            lastCell = lastRow.createCell(3);
            lastCell.setCellStyle(otherStyle);
            lastCell.setCellValue("公司盖章:");
            index++;
            index++;
            HSSFRow endLastRow = sheet.createRow(index);
            HSSFCell endLastCell = endLastRow.createCell(0);
            endLastCell.setCellStyle(otherStyle);
            endLastCell.setCellValue("监盘人:");


            try {
                workbook.write(out);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

原博主这边传的是个泛型 懒得改回来了

package cn.htd.erp.cppt.common;

import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * 包装类
 *
 * @param <T>
 */
public class ExportExcelWrapper<T> extends CPPTExportExcelUtil<T> {
    /**
     * <p>
     * 导出带有头部标题行的Excel <br>
     * 时间格式默认:yyyy-MM-dd hh:mm:ss <br>
     * </p>
     *
     * @param title 表格标题
     * @param headers 头部标题集合
     * @param list 数据集合
     * @param version 2003 或者 2007,不传时默认生成2003版本
     */
    public void exportExcel(String fileName, String title, String[] headers, List<Map<String,Object>> list, HttpServletResponse response, String version,String s) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls");
            if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
                exportExcel2003(title, headers, list, response.getOutputStream(),s);
            }else{
             //   exportExcel2007(title, headers, dataset, response.getOutputStream(), "yyyy-MM-dd HH:mm:ss");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

controller层 要注意的是 map的键要跟columnNames 对应。

   @RequestMapping("/firstInventoryDown")
    @ResponseBody
    public String firstInventoryDown(HttpServletRequest request, HttpServletResponse response){
        try {
            String taskCode = request.getParameter("taskCode1");
            Map<String,Object> map = inventoryService.getinventoryInfoByTaskCode(taskCode);
            String warehouseCodeS = (String) map.get("WAREHOUSE_CODE");
            List<String> warehouseCode = Arrays.asList(warehouseCodeS.split(","));
            List<Map<String,Object>> list = inventoryService.getGoodsDownInfo(warehouseCode);
            if(list.size() == 0 || list == null){
                return "该任务下没有盘点商品!";
            }

            String[] columnNames = {"仓库名称","商品代码","商品名称","盘点数","备注","单位"};
            String fileName = taskCode+"现场盘点表";
            ExportExcelWrapper<Map<String,Object>> util = new ExportExcelWrapper<Map<String,Object>>();
            util.exportExcel(fileName, fileName, columnNames, list, response, CPPTExportExcelUtil.EXCEL_FILE_2003,String.valueOf(map.get("COMPANY_NAME")));//
            inventoryService.changeInventoryStatus("1",taskCode);//开始第一次盘点
            eventRecordService.saveEventRecord(Long.parseLong(map.get("ID").toString()), DictConsts.EventDesc.YPKS, UserUtil.getCurrentUser().getName());
        }catch (Exception e){
            return "下载失败";
        }
        return "下载成功";
    }

jsp页面 注意要用表单提交

<form id="form_login1" action="${ctx}/inventory/firstInventoryDown" method="post" type="hidden">
            <input type="hidden" name="taskCode1" id = "taskCode1"/>
        </form>

js代码

$(function () {
    $('#form_login1').form({
        onSubmit: function(){
        },
        success:function(data){
        },

    });
});

function down(taskCode) {
    $("#taskCode1").val(taskCode);
    $("#form_login1").submit();
};
本项目属于机器学习的简单部分,基于为了快速理解机器学习而搭建的人工智能速成项目,大家可以根据其中的项目时间进行相关的学习.zip项目工程资源经过严格测试可直接运行成功且功能正常的情况才上传,可轻松复刻,拿到资料包后可轻松复现出一样的项目,本人系统开发经验充足(全领域),有任何使用问题欢迎随时与我联系,我会及时为您解惑,提供帮助。 【资源内容】:包含完整源码+工程文件+说明(如有)等。答辩评审平均分达到96分,放心下载使用!可轻松复现,设计报告也可借鉴此项目,该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的。 【提供帮助】:有任何使用问题欢迎随时与我联系,我会及时解答解惑,提供帮助 【附带帮助】:若还需要相关开发工具、学习资料等,我会提供帮助,提供资料,鼓励学习进步 【项目价值】:可用在相关项目设计中,皆可应用在项目、毕业设计、课程设计、期末/期中/大作业、工程实训、大创等学科竞赛比赛、初期项目立项、学习/练手等方面,可借鉴此优质项目实现复刻,设计报告也可借鉴此项目,也可基于此项目来扩展开发出更多功能 下载后请首先打开README文件(如有),项目工程可直接复现复刻,如果基础还行,也可在此程序基础上进行修改,以实现其它功能。供开源学习/技术交流/学习参考,勿用于商业用途。质量优质,放心下载使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值