excel导入、下载功能

1、excel导入、下载功能

2、首先,我们是居于maven项目进行开发引入poi,如果不是那就手动下载相应的jar包引入项目就可以了

        <!-- poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>${poi.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>${poi.version}</version>
        </dependency>

2、编写代码【excel 导入】

EXCEL工具类:

package com.ntgjj.util;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.DataFormat;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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 com.mysql.cj.x.protobuf.MysqlxCrud.Column;
/**
 * 导出Excel文档工具类
 * @date 2014-8-6
 * */
public class ExcelUtil {/**
     * 创建表
     * 对workbook添加数据
     * @param index 第几个工作表
     * @param rowIndex 从第几行开始
     * @param headList 表头数据
     * @param dataList 数据
     * @param hmap 字段对照如"name"对应的列为1
     * @param shellName 工作表的名称
     * @return
     */
    public static Workbook addWorkBookData(int index,int rowIndex,List<String> headList,List<?> dataList,Map<String,Integer> hmap,String shellName) {
        if(shellName == null || "".equals(shellName)) {
            shellName = "数据";
        }
        Sheet wsheet = null;
        Workbook workbook = new HSSFWorkbook();
        if (index > 0) {
            wsheet = workbook.getSheetAt(index);
        } else {
            wsheet = workbook.createSheet(shellName);
        }
        // 用于格式化单元格的数据
        // DataFormat format = workbook.createDataFormat();
        Font font = workbook.createFont();
        font.setFontHeightInPoints((short) 16); // 字体高度
        font.setColor(Font.COLOR_NORMAL); // 字体颜色正常类型的黑色。
        font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 宽度
        font.setItalic(false); // 是否使用斜体
        font.setFontName("宋体");
        // 设置单元格类型
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);
        cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
        cellStyle.setWrapText(true);
        // 设置边框
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);  
        // 自动换行  
        cellStyle.setWrapText(false);  
        // 创建行
        Row row = wsheet.createRow(0);
        if (headList != null) {
            int listSize = headList.size();
            for (int i = 0; i < listSize; i++) {
                Cell cell = row.createCell(i);
                cell.setCellValue(headList.get(i));
                cell.setCellStyle(cellStyle);// 设置单元格样式
                cell.setCellType(Cell.CELL_TYPE_STRING);// 指定单元格格式:数值、公式或字符串
                wsheet.autoSizeColumn((short)i); // 调整第一列宽度
            }
        }
        
        // 用于格式化单元格的数据
        // DataFormat format = workbook.createDataFormat();
        Font fontD = workbook.createFont();
        fontD.setFontHeightInPoints((short) 10); // 字体高度
        fontD.setColor(Font.COLOR_NORMAL); // 字体颜色正常类型的黑色。
        fontD.setBoldweight(Font.BOLDWEIGHT_BOLD); // 宽度
        fontD.setItalic(false); // 是否使用斜体
        fontD.setFontName("宋体");
        // 设置单元格类型
        CellStyle cellStyleD = workbook.createCellStyle();
        cellStyleD.setFont(fontD);
        cellStyleD.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
        cellStyleD.setWrapText(true);
        // 设置边框
        cellStyleD.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyleD.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyleD.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyleD.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 添加数据
        if (dataList != null) {
            int dlen = dataList.size();
            for (int i = 0; i < dlen; i++) {
                // 开始创建行
                Row rowData = wsheet.createRow(i+rowIndex);
                //这是序号列
                Cell row_col_cell0 = rowData.createCell(0);
                row_col_cell0.setCellValue(i+1);
                row_col_cell0.setCellStyle(cellStyleD);
                FormMap<String, Object> fl = (FormMap<String, Object>) dataList.get(i);
                if (hmap != null && hmap.size() > 0) {
                    for (String mkey : hmap.keySet()) {
                        Integer colIndex = hmap.get(mkey);
                        // 对应的值
                        String colVal = fl.get(mkey)+"";
                        Cell row_col_cell = rowData.createCell(colIndex);
                        row_col_cell.setCellValue(colVal);
                        row_col_cell.setCellStyle(cellStyleD);
                    }
                }
            }
        }
        return workbook;
    }
    
    /**
     * 将读取到的excel文件转为List<FormMap<String, Object>>对象
     * @param in excels文件流
     * @param fileName 文件名
     * @param index 读取的文件工作表,默认0
     * @param hmap 字段对照表
     * @return  List<FormMap<String, Object>>
     * @throws Exception
     */
    public static HashMap<String,FormMap<String, Object>> getFormMap(InputStream in, String fileName,int index,Map<String,Integer> hmap) throws Exception {
        HashMap<String,FormMap<String, Object>> hashFormMap = null;
        Workbook wb;
        if (in != null) {
            hashFormMap = new HashMap<String,FormMap<String, Object>>();
            // 创建Excel工作薄
            wb = new HSSFWorkbook(in);
            if(index < 0) {
                index = 0;
            }
            //获得需要读取的数据表
            Sheet wsheet = wb.getSheetAt(index);
            for (Row row : wsheet) {
                 int rowNum = row.getRowNum();
                //跳出第一行   一般第一行都是表头没有数据意义
                if(rowNum == 0){
                    continue;
                }
                FormMap<String, Object> fm = new FormMap<String, Object>();
                String grzh = "";
                if (hmap != null && hmap.size() > 0) {
                    for (String mkey : hmap.keySet()) {
                        Integer colIndex = hmap.get(mkey);
                        Cell cell_da = row.getCell(colIndex);
                        int celltype = cell_da.getCellType();
                        String value = null;
                        switch (celltype) {
                        case Cell.CELL_TYPE_STRING:
                            //String类型
                            value = cell_da.getStringCellValue();
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            //Numer类型
                            value = cell_da.getNumericCellValue()+"";
                            break;
                        default:
                            break;
                        }
                        if(value != null && !"".equals(value) && "GRZH".equals(mkey)) {
                            grzh = value.replaceFirst(" ", "");
                        }
                        fm.put(mkey, value);
                    }
                }
                hashFormMap.put(grzh,fm);
            }
            return hashFormMap;
        }
        return null;
    }
}

controler层:

@RequestMapping("importDwhjEexceFile")
    @ResponseBody
    public String importDwhjEexceFile(HttpServletRequest request) {
try {
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
            InputStream in = null;
            MultipartFile file = mRequest.getFile("importFile");
            if (file.isEmpty()) {
                throw new Exception("文件不存在!");
            }
            in = file.getInputStream();
            String fnm = file.getOriginalFilename();
            Map<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("XINGMING", 1);
            hmap.put("GRZH", 2);
            hmap.put("YJCEHJ", 3);
            //------start 开始解析数据
            HashMap<String, FormMap<String, Object>> hashFormMap = ExcelUtil.getFormMap(in, fnm,0,hmap);
            //------end 开始解析数据
        } catch (Exception e) {
            e.printStackTrace();
            return "Exception";
        }
    }

EXCEL文档在线生成并下载:

/**
     * 下载excel模板
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping("downloadDwhjEexceFile")
    @ResponseBody
    public void downloadDwhjEexceFile(HttpServletRequest request, HttpServletResponse response)
            throws Exception {//从数据库获取需要导出的数据
        List<BisJjmcFormMap> jjList = gjMapper.findBisHjPage();
        Workbook wb = null;
        String name = "模板-单位汇缴-名册";
        String fileName = name+".xls";

        if(null != jjList && jjList.size() > 0) {
            List<String> headList = new ArrayList<String>();
            //第二步 创建表头
            headList.add("序号");
            headList.add("姓名");
            headList.add("账号");
            headList.add("缴存合计(元)");
            //第三步 写入每一行数据
            Map<String, Integer> hmap = new HashMap<String, Integer>();
            hmap.put("XINGMING", 1);
            hmap.put("GRZH", 2);
            hmap.put("YJCEHJ", 3);
            wb = ExcelUtil.addWorkBookData(0, 1,headList, jjList, hmap,name+"-数据");
        }
        
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("UTF-8");
        java.io.BufferedOutputStream bos = null;
        try {
            response.setContentType("application/x-msdownload;");
            response.setHeader("Content-disposition",
                    "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1"));
            bos = new BufferedOutputStream(response.getOutputStream());
            if(wb != null) {
                //写excel
                wb.write(bos);
                bos.flush();
            }
        } catch (Exception e) {
            logger.warn(fileName+"文件下载异常!"+e.fillInStackTrace());
        } finally {
            if (bos != null)
                bos.close();
            wb = null;
        }
    }

3、顺便写一下HTML-JS代码:

 1 function  import_or_export_excel_fun(){
 2     var root_div = document.createElement("div");
 3     root_div.style = 'text-align: center;';
 4     var root_div_form = document.createElement("form");
 5     var root_div_form_input = document.createElement("input");
 6     root_div_form_input.type = 'file';
 7     root_div_form_input.id = 'excelFile';
 8     root_div_form_input.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel';
 9     root_div_form_input.style = 'padding-left: 10px;border-radius: 20px;background-color: #2281e0;color: #ffffff;';
10     var root_div_form_a = document.createElement("a");
11     root_div_form_a.value = '仅允许导入“xls”或“xlsx”格式文件!';
12     root_div_form.appendChild(root_div_form_input);
13     root_div_form.appendChild(root_div_form_a);
14     root_div.appendChild(root_div_form);
15     if(this){
16         if(this.id == 'import_excel'){
17             // 导入employee
18             layer.open({
19                 title:"excel文件导入",
20                 content: root_div.innerHTML
21                  ,btn: ['确认导入', '下载模板'] // 可以无限个按钮
22                  ,yes: function(index, layero){
23                      debugger
24                     // 按钮的回调
25                      var f_importForm_f = $("#excelFile")[0];
26                        var fileObj_fs = f_importForm_f.files; // js 获取文件对象
27                        var fs = fileObj_fs[0];
28                        //var file = $("#excelFile")[0].files[0];// 获取文件
29                        //name "shuidian.xlsx"  size 10112
30                        if(fs && fs.size > 0){
31                            var importUrl = rootPath + '/business/gj/importDwhjEexceFile.shtml';
32                            var formFile = new FormData();
33                            formFile.append("action", importUrl);
34                            formFile.append("importFile", fs); // 加入文件对象
35                            lr.ajax({
36                                type : "post",
37                                data :formFile,
38                                url : importUrl,
39                                contentType: false,// 且已经声明了属性enctype="multipart/form-data",所以这里设置为false
40                                processData: false, // 不需要对数据做处理
41                                dataType : 'json',// 这里的dataType就是返回回来的数据格式了html,xml,json
42                                async : true, // 是否异步
43                                cache : false,// 设置是否缓存,默认设置成为true,当需要每次刷新都需要执行数据库操作的话,需要设置成为false
44                                success : function(data) {
45                                     if(data == 'NOT_DATA'){
46                                         msgd('导入失败',2,'数据错误,请先生成缴交名册!');
47                                     }else if(data == 'Exception'){
48                                         msgd('导入excel异常',2,'异常错误!');
49                                     }else if(data == 'success'){
50                                         msgd('导入excel成功',1,'导入成功!');
51                                     }else if(data == 'OK'){
52                                         msgd('成功提示',1,'导入excel成功!');
53                                         gridHjsq.loadData();
54                                     }
55                                     IS_EISABLE = true;
56                                     gridHjsq.loadData();
57                                     getjcxx(true);
58                               },erro : function(data) {
59                                   msgd('错误',2,'导入Excel出错!');
60                               }
61                        });
62                        }else{
63                            msgd('提示',2,'请选择Excle文件!');
64                            return false;
65                        }
66                  },btn2:function(index, layero){
67                      var lay_ui;
68                     //下载模板前校验是否存在名册
69                      beforeDownCheck(lay_ui);
70                  }
71                  });
72         }else{
73              var lay_ui;
74             //下载模板前校验是否存在名册
75              beforeDownCheck(lay_ui);
76         }
77     }
78 }

 

转载于:https://www.cnblogs.com/ywf520/p/11584025.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值