java实现下载excel读取与生成超详细

若如初见. 提交于 2020-03-11 17:24:19

背景:没啥背景,就是要做这个功能
在这里插入图片描述
创建ExcelUtil工具类,具体导入导出方法如下

/**
 * excel导入
 * @param inputStream 导入的excel文件
 * @return
 */
public static List<Invt> excelToShopIdList(InputStream inputStream) {
    List<Invt> list = new ArrayList<>();
    Workbook workbook = null;
    try {
        workbook = WorkbookFactory.create(inputStream);
        inputStream.close();
        //工作表对象
        Sheet sheet = workbook.getSheetAt(0);
        //总行数
        int rowLength = sheet.getLastRowNum();
        //            System.out.println("总行数有多少行" + rowLength);
        //工作表的列
        Row row = sheet.getRow(0);
        //总列数
        int colLength = row.getLastCellNum();
        //            System.out.println("总列数有多少列" + colLength);
        //得到指定的单元格
        Cell cell = row.getCell(0);
        for (int i = 0; i <= rowLength; i++) {
            Invt jiFenExcel = new Invt();
            row = sheet.getRow(i);
            //循环获取每列excel内容
            for (int j = 0; j < colLength; j++) {
                //列:                    cell = row.getCell(j);
                //                    System.out.print(cell + ",");
                if (cell != null) {
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    String data = cell.getStringCellValue();
                    data = data.trim();
                    //                        System.out.print(data);
                    //                        if (StringUtils.isNumeric(data)) {
                    if (j == 0) {
                        jiFenExcel.settId(data);
                    } else if (j == 1) {
                        jiFenExcel.setNumber(Integer.parseInt(data));
                    }
                }
            }
            list.add(jiFenExcel);
            //                System.out.println("====");
        }
    } catch (Exception e) {
    }
    return list;
}

excel导出

/**
 * 导出数据生成excel
 * @param sheetName excel表格名
 * @param title 表格标题
 * @param values 表格数据集
 * @param wb excel文件
 * @return
 */
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
    // 第一步,创建一个HSSFWorkbook,对应一个Excel文件
    if (wb == null) {
        wb = new HSSFWorkbook();
    }

    // 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
    HSSFSheet sheet = wb.createSheet(sheetName);

    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
    HSSFRow row = sheet.createRow(0);

    // 第四步,创建单元格,并设置值表头 设置表头居中
    HSSFCellStyle style = wb.createCellStyle();
    // 创建一个居中格式
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 

    // 声明列对象
    HSSFCell cell = null;

    // 创建标题
    for (int i = 0; i < title.length; i++) {
        cell = row.createCell(i);
        cell.setCellValue(title[i]);
        cell.setCellStyle(style);
    }

    // 创建内容
    for (int i = 0; i < values.length; i++) {
        row = sheet.createRow(i + 1);
        for (int j = 0; j < values[i].length; j++) {
            // 将内容按顺序赋给对应的列对象
            row.createCell(j).setCellValue(values[i][j]);
        }
    }
    return wb;
}

创建好ExcelUtil后就可以开始编写Controller层了,调用方法便能使数据在excel形式和集合形式之间变换,如果你想定向导入excel某个标题下的所有值,可以使用以下的excel导入方法

public static List<Macth> excelToMacth(InputStream inputStream) {
    List<Macth> list = new ArrayList<>();
    Workbook workbook = null;
    try {
        workbook = WorkbookFactory.create(inputStream);
        inputStream.close();
        //工作表对象
        Sheet sheet = workbook.getSheetAt(0);
        //总行数
        int rowLength = sheet.getLastRowNum();
                    System.out.println("总行数有多少行" + rowLength);
        //工作表的列
        Row row = sheet.getRow(0);

        //总列数
        int colLength = row.getLastCellNum();
                   System.out.println("总列数有多少列" + colLength);
        //得到指定的单元格
        Cell cell = row.getCell(0);
        //使用变量接收各个标题列的索引
        int rowIndex = 0;
        int nameIndex = 0;
        int numberIndex = 0 ;
        int tidIndex = 0;
        //查找索引,接收
        for (int i = 0; i <= rowLength; i++) {
            if(row.getCell(0).getStringCellValue().equals("序号") || row.getCell(0).getStringCellValue().equals("编号")){
                rowIndex = i;
                for(int j = 0; j <=colLength ; j++){
                    if(row.getCell(j).getStringCellValue().equals("名称")){
                        nameIndex = j ;
                    }else if(row.getCell(j).getStringCellValue().equals("数量")){
                        numberIndex = j ;
                    }else if(row.getCell(j).getStringCellValue().equals("**编号")){
                        tidIndex = j ;
                    }
                }
                //找到所有索引后跳出
                break;
            }
        }
        //循环存值
        for(int i = rowIndex+1 ; i<rowLength ; i++){
            Macth macth = new Macth();
            row = sheet.getRow(i);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            macth.setName(row.getCell(nameIndex).getStringCellValue().trim());
            macth.setNumber(Integer.parseInt(row.getCell(numberIndex).getStringCellValue().trim()));
            macth.setTid(row.getCell(tidIndex).getStringCellValue().trim());
            list.add(macth);
        }
    } catch (Exception e) {
        e.getMessage();
        System.out.println("ExcelUtil错误!!");
    }
    return list;
}

到这里就可以安心在控制层敲代码啦,以下是导出到excel的控制层代码:

	/**
 * 匹配数据库
 * @param response
 * @return
 */
@RequestMapping("/doubExcel")
@ResponseBody
public String doubExcel(HttpServletResponse response){
    List<Pp> listP = Service.selSql(list);
    //excel标题
    String[] title = {"id","编号","数量",};
    //excel文件名
    String fileName = "匹配信息表.xls";
    //sheet名
    String sheetName = "匹配信息表1";
    String[][] content = new String[999][title.length];
    int s =0;
    for (int i = 0; i < listP.size(); i++) {
        Pp pp = listP.get(i);
        for(int j = 0; j<pp.getList().size();j++){
            content[s][0] = String.valueOf(s+1);
            content[s][1] = pp.getTid();
            content[s][2] = String.valueOf(pp.getNumber());
            s++;
        }
    }
    HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook(sheetName, title, content, null);
    String[] title2 = {"id","生产编号","生产数量","生产图"};
    //sheet名
    String sheetName2 = "生产信息表";
    String[][] content2 = new String[99][title2.length];
    int c = 0;
    for (int i = 0; i < listP.size(); i++) {
        Pp pp = listP.get(i);
        if(pp.getList().size()==0||pp.getNNN()>0||pp.getNumber()==-1){
            content2[c][0] = String.valueOf(c+1);
            content2[c][1] = pp.getTid();
            if(pp.getNNN()==-1){
                content2[c][2] = String.valueOf(pp.getNumber());
            }else{
                content2[c][2] = String.valueOf(pp.getNNN());
            }
            content2[c][3] = pp.getdNumber();
            c++;
        }
    }
    wb = ExcelUtils.getHSSFWorkbook(sheetName2, title2, content2, wb);
    try {
        this.setResponseHeader(response, fileName);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    } catch (Exception e) {
        return "请确认格式是否正确";
    }
    return "/blController/getAll";
}
//发送响应流
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();
    }
}

还有一个小的问题,excel的导入大小默认经常不够用,加入一段pom配置即可解决:

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

如果解决不了可以试着百度 = – = …

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!