java导出excel文件的两种方式

小白第一次写博客!记录一下哈!

后台系统的管理功能需要导出excel表格,之前写过一次用的是jxl-2.6.12.jar进行导出excel,今天又试了一下利用poi进行导出,都是简单的例子,毕竟是小白啊!

一、jar包导入

jar包都在这里面啦,你也可以去官网下载

       jxl官网:https://sourceforge.net/projects/jexcelapi/postdownload

       poi官网 :http://poi.apache.org/download.html

链接:https://pan.baidu.com/s/1O94t8zKBKhyQCtaRV_dUOw 密码:p4ap

利用maven导入jxl

            <dependency>
                <groupId>net.sourceforge.jexcelapi</groupId>
                <artifactId>jxl</artifactId>
                <version>2.6.12</version>
            </dependency>

 利用maven导入poi(注意:利用maven导入jar包没反应,总是报错找不到,我只好手动添加jar包了)

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

二、利用jxl进行导出excel

package com.cupinn.boss.controller.merchant;

import com.cupinn.facade.merchant.model.resp.MerchantShopResp;

import jxl.Workbook;

import jxl.write.Alignment;
import jxl.write.Label;
import jxl.write.VerticalAlignment;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import jxl.write.biff.JxlWriteException;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.CrossOrigin;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;


@SuppressWarnings("deprecation")
@Controller
@CrossOrigin
public class DownLoadExcel {
    public static final String[] TestToXls = { "序号", "门店", "账户余额", "结算金额" };

    @SuppressWarnings("deprecation")
    public void toExcel(List<MerchantShopResp> msList, HttpServletResponse res) {
        // 这里为导出文件存放的路径
        String filePath = "C:\\Users\\cupinn\\Desktop" + UUID.randomUUID() +
            "\\";

        // 加入一个uuid随机数是因为
        // 每次导出的时候,如果文件存在了,会将其覆盖掉,这里是保存所有的文件
        File file = new File(filePath);

        if (!file.exists()) {
            file.mkdirs();
        }

        SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");

        // 给要导出的文件起名为 "测试导出数据表_时间.xls"
        String filePath1 = "门店提成表" + "_" + fmt.format(new Date()) + ".xls";
        String filePath2 = filePath + filePath1;
        WritableWorkbook wb = null;

        try {
            File file2 = new File(filePath2);

            if (!file2.exists()) { // 不存在,创建
                file2.createNewFile();
            }

            wb = Workbook.createWorkbook(file2); // 创建xls表格文件

            // 表头显示
            WritableCellFormat wcf = new WritableCellFormat();
            wcf.setAlignment(Alignment.CENTRE); // 水平居中
            wcf.setWrap(true);
            wcf.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
            wcf.setFont(new WritableFont(WritableFont.TIMES, 13,
                    WritableFont.BOLD)); // 表头字体
                                         // 加粗
                                         // 13号

            wcf.setBackground(jxl.format.Colour.PERIWINKLE);

            // 内容显示
            WritableCellFormat wcf2 = new WritableCellFormat();
            wcf2.setWrap(true); // 设置单元格可以换行
            wcf2.setAlignment(Alignment.CENTRE); // 水平居中
            wcf2.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中
            wcf2.setFont(new WritableFont(WritableFont.TIMES, 11)); // 内容字体 11号

            // 表标题
            WritableFont font0 = new WritableFont(WritableFont.createFont(
                        "微软雅黑"), 15, WritableFont.BOLD);
            WritableCellFormat wcf0 = new WritableCellFormat(font0);
            wcf0.setAlignment(Alignment.CENTRE); // 平行居中
            wcf0.setVerticalAlignment(VerticalAlignment.CENTRE); // 垂直居中

            // 导出的xls的第一页,第二页就是0换成1,“sheet1”,也可以修改为自己想要的显示的内容
            WritableSheet ws = wb.createSheet("sheet1", 0);
            // WritableSheet ws2 = wb.createSheet("sheet2", 1);//第2个sheet页
            ws.addCell(new Label(0, 0, "导出结果", wcf0)); // 代表着表格中第一列的第一行显示查询结果几个字

            ws.mergeCells(0, 0, 3, 0); // 横向:合并第一行的前4列
                                       // 导出时生成表头

            for (int i = 0; i < TestToXls.length; i++) {
                // i,代表的第几列,1,代表第2行,第三个参数为要显示的内容,第四个参数,为内容格式设置(按照wcf的格式显示)
                ws.addCell(new Label(i, 1, TestToXls[i], wcf)); // 在sheet1中循环加入表头
            }

            // 查询出来的数据,这个方法是演示所用
            // String sql = "com.Test.Service.findAllUser";// sql为mybatis框架下的路径
            // Map<String, Object> map = new HashMap<String, Object>();//
            // map里为存放前台的条件
            // map.put("prnte", this.getParameter("prnteTest"));
            // List<Test> listTest = TestService.findAllList(sql, map);
            int k = 2; // 从第三行开始写入数据

            for (int i = 0; i < msList.size(); i++) {
                ws.addCell(new Label(0, k, msList.get(i).getId().toString(),
                        wcf2));
                ws.addCell(new Label(1, k,
                        msList.get(i).getSummary().toString(), wcf2));
                ws.addCell(new Label(2, k,
                        (msList.get(i).getAmount() == null) ? "0.00"
                                                            : msList.get(i)
                                                                    .getAmount()
                                                                    .toString(),
                        wcf2));
                ws.addCell(new Label(3, k,
                        (msList.get(i).getSettleAmount() == null) ? "0.00"
                                                                  : msList.get(
                            i).getSettleAmount().toString(), wcf2));

                // ws.mergeCells(4, 5, 5,
                // 5);//合并两列,按参数顺序,意思是第4列的第五行,跟第五列的第五行合并为一个单元格
                k++;
            }

            wb.write(); // 写入,到这里已经生成完成,可以在相应目录下找到刚才生成的文件
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JxlWriteException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        } finally {
            try {
                if (wb != null) {
                    wb.close();
                }
            } catch (WriteException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 这个是我们项目中,是把刚才生成的文件,响应到前台,进行下载、保存,可省略。
        downLoadFile(filePath2, filePath1, res);
    }

    public void downLoadFile(String filePath, String filePath1,
        HttpServletResponse res) {
        FileInputStream in = null;
        ServletOutputStream out = null;
        BufferedOutputStream toOut = null;

        try {
            in = new FileInputStream(new File(filePath));

            byte[] buffer = new byte[in.available()];

            while (in.read(buffer) != -1) {
                // HttpServletResponse response =
                // this.getContext().getResponse();// 从application中得到response
                res.reset(); // 清空
                             // 设置响应的文件的头文件格式

                res.setContentType("application/octet-stream");
                res.setHeader("Content-Disposition",
                    "attachment;filename=" +
                    new String(filePath1.getBytes("GBK"), "ISO8859-1"));
                res.addHeader("Content-type", "application-download");
                // 获取响应的对象流
                out = res.getOutputStream();
                toOut = new BufferedOutputStream(out);
                toOut.write(buffer);
                toOut.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

                if (out != null) {
                    out.close();
                }

                if (toOut != null) {
                    toOut.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
@ResponseBody
    @RequestMapping(value = "/pagelist", method = { RequestMethod.POST,
            RequestMethod.GET })
    public AppResponse findPageList(
            @RequestParam(required = false) Integer type,
            @RequestParam(required = false) String keywords,
            @RequestParam(required = false) Integer isExceport,
            @ModelAttribute("pageParam") PageParam pageParam,
            HttpServletRequest req, HttpServletResponse res) throws IOException {
        PageBean pb = userjobsService.findUserjobsList(keywords, type,
                pageParam);
        List<UserJobsResp> usList = pb.getRecordList();
        if (isExceport == 1) {
            // 创建HSSFWorkbook对象(excel的文档对象)
            HSSFWorkbook wb = new HSSFWorkbook();
            // 建立新的sheet对象(excel的表单)
            HSSFSheet sheet = wb.createSheet("用户投递岗位表");
            sheet.setColumnWidth(0, 31 * 256); //设置第一列宽度31个字符
            sheet.setColumnWidth(1, 31 * 256); 
            sheet.setColumnWidth(2, 31 * 256); 
            sheet.setColumnWidth(3, 31 * 256); 
            sheet.setColumnWidth(4, 31 * 256); 
            sheet.setColumnWidth(5, 31 * 256); 
//            sheet.autoSizeColumn(1);  //宽度自适应
            // 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
            HSSFRow row1 = sheet.createRow(0);
            row1.setHeightInPoints(50);
            // 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
            HSSFCell cell = row1.createCell(0);
            // 设置单元格内容
            cell.setCellValue("用户投递岗位一览表");
            //设置样式
            HSSFCellStyle style=wb.createCellStyle();
            style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
            HSSFFont font = wb.createFont();
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗
            font.setFontHeightInPoints((short) 18); //18号字体
            style.setFont(font);
            cell.setCellStyle(style);
            // 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
            // 在sheet里创建第二行
            HSSFRow row2 = sheet.createRow(1);
            // 创建单元格并设置单元格内容
            row2.createCell(0).setCellValue("用户姓名");
            row2.createCell(1).setCellValue("公司名称");
            row2.createCell(2).setCellValue("岗位名称");
            row2.createCell(3).setCellValue("类型");
            row2.createCell(4).setCellValue("投递状态");
            row2.createCell(5).setCellValue("投递时间");
            // 在sheet里创建第三行
            int hang = 2;
            SimpleDateFormat formatter = new SimpleDateFormat(
                    "yyyy-MM-dd HH:mm:ss");
            for (UserJobsResp us : usList) {
                HSSFRow rowNext = sheet.createRow(hang++);
                rowNext.createCell(0).setCellValue(us.getUserName());
                rowNext.createCell(1).setCellValue(us.getCompanyName());
                rowNext.createCell(2).setCellValue(us.getJobsName());
                if (us.getType() == 0) {
                    rowNext.createCell(3).setCellValue("兼职");
                } else {
                    rowNext.createCell(3).setCellValue("全职");
                }
                if (us.getStatus() == 0) {
                    rowNext.createCell(4).setCellValue("申请");
                } else if (us.getStatus() == 1) {
                    rowNext.createCell(4).setCellValue("查看");
                } else if (us.getStatus() == 2) {
                    rowNext.createCell(4).setCellValue("录取");
                } else if (us.getStatus() == 3) {
                    rowNext.createCell(4).setCellValue("未录取");
                }
                rowNext.createCell(5).setCellValue(formatter.format(us.getCreatetime()));
            }
            // 输出Excel文件
            OutputStream output = res.getOutputStream();
            res.reset();
            formatter = new SimpleDateFormat("yyyyMMddHHmmss");
            String filename = "用户岗位" + formatter.format(new Date()) + ".xls";
            // 设置响应的文件的头文件格式
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename="
                    + new String(filename.getBytes("GBK"), "ISO8859-1"));
            res.addHeader("Content-type", "application-download");
            wb.write(output);
            output.close();
            return null;
        }
        return AppResponse.okList(pb);
    }


参考网址:http://www.open-open.com/lib/view/open1429847388


三、利用poi导出excel213.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值