poi 导出excel

package com.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class ExcelExportUtil {

    private final static Log logger = LogFactory.getLog(ExcelExportUtil.class);

    public static void writeOut(String fileName,List dataList, HttpServletResponse response) throws IOException {
       // response.reset();
        //response.setHeader("Content-disposition", "attachment; filename=report.xls");//文件名这里可以改
        response.setContentType("application/x-msdownload");
        //转码防止乱码
        response.addHeader("Content-Disposition", "attachment;filename="+ encodingFileName(fileName + ".xls"));
        List<String> titleNameOrderlyList = buildRiskClaimTitleName();
        export(fileName, titleNameOrderlyList, 1, dataList, response.getOutputStream());
    }

    //  excel 表头名字
    public static List<String> buildRiskClaimTitleName(){
        List<String> titleNameOrderlyList = new ArrayList<String>();
        titleNameOrderlyList.add("123");
        titleNameOrderlyList.add("435");
      
        return titleNameOrderlyList;
    }

    public static HSSFCellStyle buildStyle(HSSFWorkbook workbook, String fontName, boolean isBold){
        // 1.生成字体对象
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short)10);
        font.setFontName(fontName);
        if(isBold){
            font.setFontHeightInPoints((short)12);
            font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        }
        // 2.生成样式对象,这里的设置居中样式和版本有关,我用的poi用HSSFCellStyle.ALIGN_CENTER会报错,所以用下面的
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置居中样式
        // style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setFont(font); // 调用字体样式对象
        style.setWrapText(true);
        //设置居中样式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        return style;
    }


    public static void export(String sheetName,List<String> titleNameOrderlyList, int dataStartRow, List dataList, OutputStream outputStream) throws IOException {
        if(titleNameOrderlyList == null || dataList == null ){
            logger.info("titleNameOrderlyList_or_dataList_is_null");
            return;
        }
        logger.info("titleNameOrderlyList_size=" + titleNameOrderlyList.size() + "dataList_size=" + dataList.size());
        //创建HSSFWorkbook对象(excel的文档对象)
        HSSFWorkbook workbook = new HSSFWorkbook();
        //建立新的sheet对象(excel的表单)
        HSSFSheet sheet=workbook.createSheet();
        workbook.setSheetName(0, sheetName,(short)1);
        //在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
        HSSFCellStyle style = buildStyle(workbook, "新宋体", false);
        HSSFCellStyle headerStyle = buildStyle(workbook, "新宋体", true);

        // 表头 创建单元格(excel的单元格,参数为列索引,可以是0~255之间的任何一个
        HSSFRow row1=sheet.createRow(0);
        for (int i = 0; i < titleNameOrderlyList.size(); i++) {
            HSSFCell cellTmp = row1.createCell((short)i);
            cellTmp.setCellStyle(headerStyle);
            cellTmp.setEncoding(HSSFCell.ENCODING_UTF_16);
            String titleName = titleNameOrderlyList.get(i);
            cellTmp.setCellValue(titleName);
//            int width = titleName.getBytes().length * 256 + 1024 ;
            int width = buildWidth(titleName, (short) 0);
            sheet.setColumnWidth((short) i, (short) width);
        }

        // 数据
        for (int i = 0; i < dataList.size(); i++) {

            //从sheet第 dataStartRow 行开始填充数据
            HSSFRow dataRow = sheet.createRow(i + dataStartRow);
            Object[] objs = (Object[]) dataList.get(i);
            for (int j = 0; j < objs.length; j++) {
                // char newLine = 0x000A;// "\r\n";
                int columnWidth = sheet.getColumnWidth((short)j) ;
                HSSFCell dataCell = dataRow.createCell((short)j);
                dataCell.setCellStyle(style);
                dataCell.setEncoding(HSSFCell.ENCODING_UTF_16);
                Object val = objs[j];
                if(val !=null){
                    String valStr = String.valueOf(val);
                    int length = buildWidth(valStr, (short) 0);
                    if(length > columnWidth){
                        short width = (short) (length);
                        sheet.setColumnWidth((short) j, width );
                    }
                    dataCell.setCellValue(valStr);
                } else {
                    dataCell.setCellValue("");
                }
            }
        }
        //输出Excel文件
        workbook.write(outputStream);
        outputStream.close();
        logger.info("export_excel_ok");
    }

    public static String encodingFileName(String fileName) {
        String returnFileName = "";
        try {
            returnFileName = URLEncoder.encode(fileName, "UTF-8");
            returnFileName = StringUtils.replace(returnFileName, "+", "%20");
            if (returnFileName.length() > 150) {
                returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
                returnFileName = StringUtils.replace(returnFileName, " ", "%20");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return returnFileName;
    }

    public static boolean containChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    public static int buildWidth(String val, short oldWidth){
        boolean containChinese = containChinese(val);
        int length = val.getBytes().length ;
        if(containChinese){
            length = val.getBytes().length *256 ;
            int add = (val.length() ) * 256;
            length += add;
        }else {
            length += 2;
            length *= 256;
        }
        return length;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值