Java操作Excel导出数据到Excel文档

本文章描述使用Java开发语言来导出数据库数据到对应的模板Excel中,使其生成一个带有一定格式的Excel文档的案例,下篇文章将给大家分享一下怎样把Excel文档中的数据保存到数据库。大体分为以下三部分:

  1. 前台传入模板名称等参数
  2. 根据参数查询数据库数据
  3. 读取模板,将数据写入到模板,下载

前台参数:如查询2016年8月的数据导入excel

参数含义
tyear
tmonth
tableName物理表名
templateName模板名称
fileName导出文件名称

后台代码

public void exportExcelData(HttpServletRequest request, HttpServletResponse response) {
        //String tyear = request.getParameter("tyear");
        //String tmonth= request.getParameter("tmonth");
        // 物理表名称
        String tableName = request.getParameter("tableName");
        // 模板名称
        String templateName = request.getParameter("templateName");
        // 下载文件名
        String fileName = request.getParameter("fileName");
        try {
            if (fileName == null||fileName.trim().equals("")) {
                // 当文件名为空,取文件名为系统当前时间
                fileName = DateUtil.getUtilDateString(new Date(), "yyyyMMddHHmmssSSS");
            } else if("FF".equals(getBrowser(request))) {
                fileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1"); 
            }
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }

        //**************查询数据********************
        //读取xml配置文件
        Document document = Dom4Report.getDom(XmlConfig.XMLFILE);
        //取出pageOffice配置 获取数据库对应的列名
        String pageConfigcontent = Dom4Report.getElementChildContentByID(document ,"pageOffice");
        //取出import配置 获取excel表头名称
        String importcontent = Dom4Report.getElementChildContentByID(document ,"import");
        Map pageConfig=null;
        Map importConfig=null;
        try {
            pageConfig = JsonUtils.getObjectMapper().readValue(pageConfigcontent, Map.class);
            importConfig = JsonUtils.getObjectMapper().readValue(importcontent, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //查询表数据信息
        List<Object[]> tableData=null;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("queryColumn", pageConfig.get("columns"));//物理表字段
        int rowstart=Integer.parseInt(pageConfig.get("rowstart").toString());//获取开始行
        String columnCaptions=importConfig.get("columnCaptions").toString();//列名
        //查询数据内容
        tableData = hibernateDao.getTableData(tableName, tyear, tmonth, map);
        //设置响应格式
        response.addHeader("Content-Disposition", "attachment; filename="
                + fileName);
        response.addHeader("Content-Type", "application/vnd.ms-excel");
        // 获取模板位置 读取配置文件获取模板位置也可以读取数据库获取模板位置 如Linux服务器:file:/home/app/doc
        String templatePath = PubConfig.getProperty("EXCEL_TEMPLATE_PATH");
        if(templatePath.indexOf("file:")>=0){
            templatePath=templatePath.split("file:")[1];//去掉file:头
        }
        // 实际位置 如:/home/app/doc/xxx.xls
        String path = templatePath + File.separator +"EX"+ templateName;
        // 新建文件
        File file=new File(path);
        //获取输出流
        OutputStream out;
        try {
            // 3.通过response获取OutputStream对象(out)
            out = response.getOutputStream();
            //读入文件
            Workbook workbookin = Workbook.getWorkbook(file);
            //输出文件
            WritableWorkbook workbookout = Workbook.createWorkbook(out,workbookin);
            if(workbookin!=null&&workbookout!=null){
                //获取输出excel的第一个sheet
                WritableSheet sheet = workbookout.getSheet(0);
                // 一般样式,字体样式,标题加黑,普通正文
                WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
                // 表格设置边框,对齐方式等
                WritableCellFormat wcf_data = new WritableCellFormat(NormalFont);
                //有边框
                wcf_data.setBorder(Border.ALL, BorderLineStyle.THIN);
                wcf_data.setWrap(false);
                for (int row = 0; row < tableData.size(); ++row) {
                    Object[] dataRow = null;
                    if ((tableData.get(0) != null)
                            && (tableData.get(0).getClass().isArray())) {
                        dataRow = (Object[]) (Object[]) tableData.get(row);
                    } else {
                        dataRow = new Object[] { tableData.get(row) };
                    }

                    // 循环读取List数据,将要导出的数据写入到excel中
                    int length = columnCaptions.split(",").length;
                    for (int col = 0; col < length; ++col) {
                        if (dataRow[col] != null) {
                            String listvalue = dataRow[col].toString();
                            Label label = new Label(col, row + rowstart-1, listvalue,wcf_data);
                            sheet.addCell(label);
                        } else {
                            Label label = new Label(col, row + rowstart-1, "",wcf_data);
                            sheet.addCell(label);
                        }
                    }
                }
                //设置填报人姓名和电话
                if(tableData!=null&&tableData.size()>0&&tableData.get(0)!=null){
                    Object[] obj=tableData.get(0);
                    int objLength=obj.length;
                    String tbrName=(obj[objLength-2]==null?"":obj[objLength-2].toString());
                    String tbrPhone=(obj[objLength-1]==null?"":obj[objLength-1].toString());
                    Label labeltbrName = new Label(1, 1, tbrName);
                    sheet.addCell(labeltbrName);
                    Label labeltbrPhone = new Label(3, 1, tbrPhone);
                    sheet.addCell(labeltbrPhone);
                }
                workbookout.write();
                workbookout.close();
                //workbookin.close();
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("导出excel出现异常!");
        }
    }

XML配置

以上代码设计到读取XML文件,获取配置好的excel表头名称和对应的数据库表的列名,这样可以灵活变更模板表头和导出的数据。读取xml可以使用Dom4j技术,这里不再讲解。

<Item1 ID="import">{"columnCaptions":"表头标题1,表头标题2,表头标题3,表头标题4,表头标题5,表头标题6,表头标题7,表头标题8,表头标题9,表头标题10"}
</Item1>
<Item2 ID="pageOffice">{"columns":"COLUMN1,COLUMN2,COLUMN3,COLUMN4,COLUMN5,COLUMN6,COLUMN7,COLUMN8,COLUMN9,COLUMN10","rowstart":4}
</Item2>

注意:合理配置xml文件可以是该方法用于不同格式模板和数据的导出功能

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值