POI导出Excel

GitHub

POI导出Excel,这里封装了几个方法,在监听器中调用即可。

saveFile方法主要是选保存路径,并判断文件是否已存在,list里是从数据库查询到的数据,这里就不写了

public static void saveFile(List<Map<String, Object>> list) {
        File file = null;
        JFileChooser jFileChooser = new JFileChooser();// 文件选择器
        FileNameExtensionFilter filter = new FileNameExtensionFilter("*.xls","xls");// 文件名过滤器
        jFileChooser.setFileFilter(filter);// 给文件选择器加入文件过滤器
        File newfile = new File("新建文件.xls");
        jFileChooser.setSelectedFile(newfile);
        if (JFileChooser.APPROVE_OPTION == jFileChooser
                .showSaveDialog(jFileChooser)) {
            file = jFileChooser.getSelectedFile();

            if(file.exists()){
                int n = JOptionPane.showConfirmDialog(null,"文件已存在,是否覆盖", "提示", JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
                if (JOptionPane.YES_OPTION == n) {
                    writeexcel(list, file);
                }
            }else {
                writeexcel(list, file);
            }

        }

writeexcel方法负责创建excel,前面4步即可,许多属性默认;并创建数据流处理数据

public static void writeexcel(List<Object[]> list, File file) {
        // 1.声明工作簿
        HSSFWorkbook excel = new HSSFWorkbook();
        // 2.创建工作表
        sheet = excel.createSheet("客户信息");
        // 3.为工作表添加行
        HSSFRow firstRow = sheet.createRow(0);
        // 4.添加单元格
        HSSFCell cells[] = new HSSFCell[3];

        insertCell(list);

        OutputStream out = null;

        try {

            out = new FileOutputStream(file);

            excel.write(out);

            out.close();

        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

insertCell方法:插入数据到单元格,这里是按行插入数据;如果要按列插入数据,可以把行封装到List里,遍历数据做createRow,并把它添加到List里,在循环遍历插入数据。

public static void insertCell(List<Object[]> list) {
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {

                HSSFRow row = sheet.createRow(i);
                Object[] object = list.get(i);
                for (int j = 0; j < object.length; j++) {
                    HSSFCell cell = row.createCell(j);
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(object[j]);
                    String str = stringBuffer.toString();
                    cell.setCellValue(str);
                }
            }
        }
    }

这里写图片描述

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值