美文网首页
java导出导入excel

java导出导入excel

作者: IT小池 | 来源:发表于2020-03-19 19:27 被阅读0次

    首先导包

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.0</version>
    </dependency>
    

    创建 ExcelUtil.java

    package com.example.util;
    
    import org.apache.poi.hssf.usermodel.*;
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.ss.util.CellRangeAddress;
    
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    /**
     * Excel工具类
     */
    public class ExcelUtil {
    
        /**
         * 导入 Excel 数据
         * @param filePath excel文件所在路径(一般先上传在读取)
         * @param fields 字段数组
         * @param startRowNum 从excel哪一行开始读
         * @return
         * @throws IOException
         */
        public static List<Map<String,Object>> read(String filePath, List<String> fields, int startRowNum) throws IOException {
            InputStream is = new FileInputStream(filePath);
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
            List<Map<String,Object>> list = new ArrayList<>();
            // 循环工作表Sheet
            for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
                HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
                if (hssfSheet == null) {
                    continue;
                }
                // 循环行Row
                for (int rowNum = startRowNum; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                    HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                    Map<String,Object> map = new HashMap<>();
                    for (int i = 0,leng=fields.size(); i < leng; i++) {
                        map.put(fields.get(i),hssfRow.getCell(i));
                    }
                    list.add(map);
                }
            }
            return list;
        }
    
        /** 导出 Excel
         * @param title 标题
         * @param headers  表头
         * @param values  表中元素
         * @return
         */
        public static HSSFWorkbook getHSSFWorkbook(String title, String headers[], String [][] values){
            //创建一个HSSFWorkbook,对应一个Excel文件
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
            //在workbook中添加一个sheet,对应Excel文件中的sheet
            HSSFSheet hssfSheet = hssfWorkbook.createSheet(title);
            //创建标题合并行
            hssfSheet.addMergedRegion(new CellRangeAddress(0,(short)0,0,(short)headers.length - 1));
            //设置标题样式
            HSSFCellStyle style = hssfWorkbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);   //设置居中样式
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            //设置标题字体
            Font titleFont = hssfWorkbook.createFont();
            titleFont.setFontHeightInPoints((short) 14);
            style.setFont(titleFont);
            //设置值表头样式 设置表头居中
            HSSFCellStyle hssfCellStyle = hssfWorkbook.createCellStyle();
            hssfCellStyle.setAlignment(HorizontalAlignment.CENTER);   //设置居中样式
            hssfCellStyle.setBorderBottom(BorderStyle.THIN);
            hssfCellStyle.setBorderLeft(BorderStyle.THIN);
            hssfCellStyle.setBorderRight(BorderStyle.THIN);
            hssfCellStyle.setBorderTop(BorderStyle.THIN);
            //设置表内容样式
            //创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle style1 = hssfWorkbook.createCellStyle();
            style1.setBorderBottom(BorderStyle.THIN);
            style1.setBorderLeft(BorderStyle.THIN);
            style1.setBorderRight(BorderStyle.THIN);
            style1.setBorderTop(BorderStyle.THIN);
            //产生标题行
            HSSFRow hssfRow = hssfSheet.createRow(0);
            HSSFCell cell = hssfRow.createCell(0);
            cell.setCellValue(title);
            cell.setCellStyle(style);
            //产生表头
            HSSFRow row1 = hssfSheet.createRow(1);
            for (int i = 0; i < headers.length; i++) {
                HSSFCell hssfCell = row1.createCell(i);
                hssfCell.setCellValue(headers[i]);
                hssfCell.setCellStyle(hssfCellStyle);
            }
            //创建内容
            for (int i = 0; i <values.length; i++){
                row1 = hssfSheet.createRow(i +2);
                for (int j = 0; j < values[i].length; j++){
                    //将内容按顺序赋给对应列对象
                    HSSFCell hssfCell = row1.createCell(j);
                    hssfCell.setCellValue(values[i][j]);
                    hssfCell.setCellStyle(style1);
                }
            }
            return hssfWorkbook;
        }
    }
    

    使用方式:

    package com.example.controller;
    
    
    import com.example.util.ExcelUtil;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Date;
    import java.util.List;
    import java.util.Map;
    
    
    @RestController
    public class TestController {
        // 导入 excel 读取数据
        public static void main(String[] args) {
            // 先上传 excel 然后在读取数据
            String path = "D:\\upload\\2020\\03\\19\\8aa9eb5d886a4dc6bc7f091137c01084.xls";
            String[] fields = {"id","name","password","phone","time"};
            try {
                List<Map<String, Object>> result = ExcelUtil.read(path, Arrays.asList(fields),2);
                System.out.println(result);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 导出 excel
         * @param request
         * @param response
         * @throws Exception
         */
        @RequestMapping(value = "/export")
        @ResponseBody
        public void export(HttpServletRequest request, HttpServletResponse response) throws Exception {
            //获取数据
            List<PageData> list = new ArrayList<>();
            Date date = new Date();
            for (int i = 0; i < 10; i++) {
                PageData pageData = new PageData();
                pageData.setId("00"+i);
                pageData.setUsername("小池" + i);
                pageData.setPassword("123"+i);
                pageData.setCreateTime(date);
                pageData.setPhone("135"+i);
                list.add(pageData);
            }
    
            //excel标题
            String[] headers = {"用户ID", "用户名称", "用户密码", "用户手机","创建时间"};
    
            //excel文件名
            String fileName = "用户信息表" + System.currentTimeMillis() + ".xls";
    
            //excel sheet名
            String title = "用户信息表";
    
            String [][] content = new String[list.size()][5];
            for (int i = 0; i < list.size(); i++) {
                content[i] = new String[headers.length];
                PageData obj = list.get(i);
                content[i][0] = obj.getId().toString();
                content[i][1] = obj.getUsername();
                content[i][2] = obj.getPassword();
                content[i][3] = obj.getPhone();
                content[i][4] = obj.getCreateTime().toString();
            }
            //创建HSSFWorkbook
            HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(title, headers, content);
            //响应到客户端
            try {
                // 设置响应头信息
                this.setResponseHeader(response, fileName);
                OutputStream os = response.getOutputStream();
                wb.write(os);
                os.flush();
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        /**
         * 发送响应流方法
         */
        public void setResponseHeader(HttpServletResponse response, String fileName) {
            try {
                try {
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                response.setContentType("application/octet-stream;charset=ISO8859-1");
                response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
                response.addHeader("Pargam", "no-cache");
                response.addHeader("Cache-Control", "no-cache");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:java导出导入excel

          本文链接:https://www.haomeiwen.com/subject/hexryhtx.html