使用POI导出excell文件

使用POI导出excell文件

工作中我们经常会遇到将数据导出的情况,excell文件是目前用的比较多的文件格式,下面说一下如何导出excell文件

引入Maven依赖

<!--解析excell文件的poi包-->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.11</version>
        </dependency>

请求接口,导出代码:

import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
@RestController
@RequestMapping(value = "/im/product",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TestController extends BaseController {
/**
     * 产品信息导出
     * @param
     * @return
     */
    @RequestMapping(value = "/exportProductInfoByQueryDto", method = RequestMethod.GET)
    @ApiOperation(httpMethod = "GET",value = "产品信息导出")
    public Wrapper testexportByQueryDto(HttpServletResponse response, HttpServletRequest request,
                                        @RequestParam(value = "name", required = false) String name,
                                        @RequestParam(value = "code", required = false) String code,
                                        @RequestParam(value = "productName", required = false) String productName,
                                        @RequestParam(value = "systemTypeName", required = false) String systemTypeName,
                                        @RequestParam(value = "displayStatus", required = false) Integer displayStatus){
        logger.info("产品信息导出请求参数:{}",name,code,productName,systemTypeName,displayStatus);
        try{
            Map queryMap = Maps.newHashMap();
            queryMap.put("name", name);
            queryMap.put("code", code);
            queryMap.put("productName", productName);
            queryMap.put("systemTypeName", systemTypeName);
            queryMap.put("displayStatus", displayStatus);
            List<SccProductPricePackagePageVo> sccProductPricePackagePageVoList = sccProductPricePackageService.querySccProductPriceByQueryVoDto(queryMap);
            if (CollectionUtils.isEmpty(sccProductPricePackagePageVoList)) {
                return WrapMapper.wrap(ErrorCodeEnum.SCC10061017);
            }
            //写入Excel
            //在内存中创建一个excel
            XSSFWorkbook hb = new XSSFWorkbook();
            //创建sheet标签页
            XSSFSheet createSheet = hb.createSheet(PRODUCT_PACKAGE_EXPORT_NAME);
            //创建标题行
            XSSFRow createRow = createSheet.createRow(0);
            createRow.createCell(0).setCellValue("套餐编号");
            createRow.createCell(1).setCellValue("套餐名称");
            createRow.createCell(2).setCellValue("价格(元)");
            createRow.createCell(3).setCellValue("有效期(月)");
            createRow.createCell(4).setCellValue("归属产品");
            createRow.createCell(5).setCellValue("体系名称");
            createRow.createCell(6).setCellValue("企业数");
            createRow.createCell(7).setCellValue("状态");
//            createRow.createCell(8).setCellValue("创建时间");
            //循环写入数据
            for (SccProductPricePackagePageVo sccProductPricePackagePageVo : sccProductPricePackagePageVoList) {
                int lastRowNum = createSheet.getLastRowNum();
                XSSFRow createRow2 = createSheet.createRow(lastRowNum+1);
                createRow2.createCell(0).setCellValue(sccProductPricePackagePageVo.getCode());
                createRow2.createCell(1).setCellValue(sccProductPricePackagePageVo.getName());
                BigDecimal price = sccProductPricePackagePageVo.getPrice();
                double dPrice = price.doubleValue();
                DecimalFormat decimalFormat = new DecimalFormat(".00");//构造方法的字符格式这里如果小数不足2位,会以0补足.
                String priceFormat = decimalFormat.format(dPrice);
                createRow2.createCell(2).setCellValue(priceFormat);
                createRow2.createCell(3).setCellValue(sccProductPricePackagePageVo.getValidMonths());
                createRow2.createCell(4).setCellValue(sccProductPricePackagePageVo.getProductName());
                createRow2.createCell(5).setCellValue(sccProductPricePackagePageVo.getSystemTypeName());
                createRow2.createCell(6).setCellValue(sccProductPricePackagePageVo.getEnterpriseNumbers() == null ? 0: sccProductPricePackagePageVo.getEnterpriseNumbers());
                createRow2.createCell(7).setCellValue(sccProductPricePackagePageVo.getDisplayStatus() == 0 ? "已上架" : "已下架");
//                createRow2.createCell(8).setCellValue(CalendarUtil.getFormatDate(sccProductPricePackagePageVo.getCreatedTime()));
            }
            //循环写入数据
            String fileName = PRODUCT_PACKAGE_EXPORT_NAME + ".xlsx";
            //获取当前浏览器
            String agent = request.getHeader("User-Agent");
            //通过输出流写回浏览器 下载    一个流
            ServletOutputStream outputStream = response.getOutputStream();
            //另一个头信息
            fileName = FileUtils.encodeDownloadFilename(fileName, agent);
            //文件名转码
//            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.setContentType("application/octet-stream");
            response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
//            response.setHeader("Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
            //告诉客户端下载文件
            response.setHeader("content-disposition", "attachment; filename=" + fileName);
            hb.write(outputStream);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("导出产品信息异常" + ErrorCodeEnum.GL99990500);
        }finally {
            logger.info("导出产品成功!");
        }
        return null;
    }
    }

FileUtils 类

public class FileUtils {
		/**
		 * 下载文件时,针对不同浏览器,进行附件名的编码
		 * 
		 * @param filename
		 *            下载文件名
		 * @param agent
		 *            客户端浏览器
		 * @return 编码后的下载附件名
		 * @throws IOException
		 */
		public static String encodeDownloadFilename(String filename, String agent)
				throws IOException {
			if (agent.contains("Firefox")) { // 火狐浏览器
				filename = new BASE64Encoder().encode(filename.getBytes("utf-8")) + "?=";
				filename = filename.replaceAll("\r\n", "");
			} else { // IE及其他浏览器
				filename = URLEncoder.encode(filename, "utf-8");
				filename = filename.replace("+"," ");
			}
			return filename;
		}
}

查询mybatis接口

<select id="queryExportSccProductPrice" parameterType="java.util.Map" resultMap="PageVoMap">
        SELECT
        t1.id,
        t1.code,
        t1.name,
        t1.price,
        t1.product_id,
        t1.product_name,
        t1.system_type_id,
        t1.system_type_name,
        t1.valid_months,
        t1.display_status,
        t1.created_time,
        t1.enterprise_numbers,
        t2.national_standard,
        t2.international_standard
        from
        scc_product_price_package t1 ,scc_system_type t2
        <where>
            <if test="code != null and code != ''">
                t1.code like '%${code}%'
            </if>
            <if test="name != null and name != ''">
                and t1.name like '%${name}%'
            </if>
            <if test="productName != null and productName != ''">
                and t1.product_name like '%${productName}%'
            </if>
            <if test="systemTypeName != null and systemTypeName != ''">
                and t1.system_type_name like '%${systemTypeName}%'
            </if>
            <if test="displayStatus != null">
                and t1.display_status = #{displayStatus}
            </if>
            and t1.system_type_id = t2.id and t1.status = 0 and t2.status = 0
        </where>
        order by id asc
    </select>

PageVoMap

<resultMap id="PageVoMap" type="com.isosaas.isocloud.service.scc.vo.SccProductPricePackagePageVo">
        <id column="id" jdbcType="BIGINT" property="id" />
        <result column="code" jdbcType="VARCHAR" property="code" />
        <result column="name" jdbcType="VARCHAR" property="name" />
        <result column="price" jdbcType="DECIMAL" property="price" />
        <result column="valid_months" jdbcType="INTEGER" property="validMonths" />
        <result column="product_id" jdbcType="BIGINT" property="productId" />
        <result column="product_name" jdbcType="VARCHAR" property="productName" />
        <result column="system_type_id" jdbcType="BIGINT" property="systemTypeId" />
        <result column="system_type_name" jdbcType="VARCHAR" property="systemTypeName" />
        <result column="display_status" jdbcType="INTEGER" property="displayStatus" />
        <result column="enterprise_numbers" jdbcType="INTEGER" property="enterpriseNumbers" />
        <result column="created_time" jdbcType="TIMESTAMP" property="createdTime" />
        <result column="national_standard" jdbcType="VARCHAR" property="nationalStandard" />
        <result column="international_standard" jdbcType="VARCHAR" property="internationalStandard" />
    </resultMap>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值