Java实现导出Excel

Posted dslnn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现导出Excel相关的知识,希望对你有一定的参考价值。

项目中实现的代码:

一.
//controller @RequestMapping(value = "/exportAccountManager") public void exportAccountManager(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName, String orgNo, String consNo, String consName, Integer consState) { String templateFileName = request.getSession().getServletContext().getRealPath("/") + "resources/templates/" + fileName; try (InputStream input = new BufferedInputStream(new FileInputStream(templateFileName)); OutputStream output = response.getOutputStream();) { Map<String, Object> params = buildParam(orgNo, consNo, consName, consState); List<AccountManagerModel> dataList = accountManagerService.queryAccountManagerList(params); CommonUtils.exportExcel(response, fileName, "客户清单.xls", input, output, dataList); } catch (Throwable ex) { LOGGER.error("导出客户清单失败:", ex); } } //参数 private Map<String, Object> buildParam(String orgNo, String consNo, String consName, Integer consState) { Map<String, Object> params = new HashMap<String, Object>(); CommonUtils.addOrgParam(orgNo, commonService, params); params.put("consNo", consNo); params.put("consName", consName); params.put("consState", consState); return params; } 二.工具类中导出相关 public static void exportExcel(HttpServletResponse response, String fileName, String cnFileName, InputStream input, OutputStream output, List<?> dataList) throws IOException { cnFileName = URLEncoder.encode(cnFileName, StandardCharsets.UTF_8.name()); response.setHeader("Content-Disposition", "attachment;filename=" + cnFileName); response.setContentType("application/vnd.ms-excel"); Map<String, Object> params = new HashMap<String, Object>(); params.put("dataList", dataList); exportExcel(input, output, params); output.flush(); } public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> params) throws IOException { Context context = PoiTransformer.createInitialContext(); if (MapUtils.isNotEmpty(params)) { Iterator<Map.Entry<String, Object>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> entry = iterator.next(); context.putVar(entry.getKey(), entry.getValue()); } } JxlsHelper jxlsHelper = JxlsHelper.getInstance(); Transformer transformer = jxlsHelper.createTransformer(is, os); JexlExpressionEvaluator evaluator = (JexlExpressionEvaluator) transformer.getTransformationConfig() .getExpressionEvaluator(); evaluator.getJexlEngine().setSilent(true); // 设置静默模式,不报警告 // 函数强制,自定义功能 Map<String, Object> funcs = new HashMap<String, Object>(); funcs.put("utils", new JxlsUtils()); evaluator.getJexlEngine().setFunctions(funcs); // 必须要这个,否者表格函数统计会错乱 jxlsHelper.setUseFastFormulaProcessor(false).processTemplate(context, transformer); } 三.service @Override public List<AccountManagerModel> queryAccountManagerList(Map<String, Object> params) throws Exception { return accountManagerMapper.queryAccountManagerList(params); } //service接口 public List<AccountManagerModel> queryAccountManagerList(Map<String, Object> params) throws Exception; 四.mapper //mapper接口 public List<AccountManagerModel> queryAccountManagerList(Map<String, Object> params) throws Exception; ////mapper映射xml
<select id="queryAccountManagerList" parameterType="java.util.Map" resultMap="AccountManagerResultMap">
        select 
            a.cons_id,
            a.cons_no,
            a.cons_name,
            a.cons_address,
            a.legal_person,
            a.legal_person_phone,
            a.bill_person,
            a.bill_person_phone,
            a.electric_person,
            a.electric_person_phone,
            a.entrusted_person,
            a.entrusted_person_phone,
            a.cons_state,
            a.org_no,
            b.org_name
       from be_cons_info a, o_org b
      where a.org_no = b.org_no
        <if test="orgNo != null and orgNo != ‘‘">
            and FIND_IN_SET(a.org_no, #{orgNo})
        </if>
        <if test="consNo != null and consNo != ‘‘">
            and a.cons_no like concat(‘%‘, #{consNo}, ‘%‘)
        </if>
        <if test="consName != null and consName != ‘‘">
            and a.cons_name like concat(‘%‘, #{consName}, ‘%‘)
        </if>
        <if test="consState != null">
            and a.cons_state = #{consState}
        </if>
        <if test="powerCompany != null and powerCompany != ‘‘">
            and b.org_name like concat(‘%‘, #{powerCompany}, ‘%‘)
        </if>
    </select>

 五.前端html

<div class="tool_wrapper">
        <button class="ui-btn ui-btn-primary" onclick="addAccountManager();">新增</button>
        <button class="ui-btn ui-btn-primary left20" onclick="editAccountManager();">修改</button>
        <!-- <button class="ui-btn ui-btn-primary left20" onclick="cancelAccountManager();">注销</button> -->
        <button class="ui-btn ui-btn-primary left20 fileinput-button">
            <span>导入Excel</span>
            <input id="fileupload" type="file" name="file" accept="application/vnd.ms-excel">
        </button>
        <button class="ui-btn ui-btn-primary left20" onclick="exportXls()">导出Excel</button>
        <button class="ui-btn ui-btn-primary left20" onclick="downloadXlsTemplate()">下载模板</button>
    </div>

六.js

function exportXls() {
    var params = getSearchTableParams();
    var url = getUrl("accountManager/exportAccountManager?fileName=cons.xls", params, true);
    window.location.href = basePath + url;
}

 

/**
 * 获取查询表格参数
 * @returns Array
 */
function getSearchTableParams() {
  var params = [];
  $(".search_table input,.search_table select").each(function () {
    var _this = $(this);
    params.push({
      name: _this.attr(‘name‘),
      value: _this.val()
    });
  });
  return params;
}

/**
 * 获取URL
 *
 * @param url URL
 * @param params URL参数
 * @param urlContainParam URL是否包含参数,默认不含参数
 * @returns
 */
function getUrl(url, params, urlContainParam) {
  if (params == null || params.length == 0)
    return url;
  if (urlContainParam == null)
    urlContainParam = false;
  var arr = [url];
  $(params).each(function (i, e) {
    if (i == 0 && urlContainParam == false) {
      arr.push("?" + e.name + "=" + e.value);
    } else {
      arr.push("&" + e.name + "=" + e.value);
    }
  });
  return arr.join(‘‘);
}

 


以上是关于Java实现导出Excel的主要内容,如果未能解决你的问题,请参考以下文章

java五行代码导出Excel

java把数据导出为excel,如何实现每十条数据导入一个excel中,每十条数据导入一个excel中

java端导出Excel表格。

java 实现导出Excel文件

Java后端实现Excel导入导出功能

java代码怎么实现 excel导入的文本值转换成日期