导出Excel数据的工具类

最近在做项目使用的导出Excel数据的工具类,在此粘贴出来提供给大家使用参考和使用,代码如下:

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelUtils {
   
    private static final Logger logger = LoggerFactory .getLogger(ExcelUtils.class);
   
    /**
     * 导出Excel数据
     * @param fileName 文件名
     * @param headers 列头标题
     * @param list    数据集合
     */
    public static void writeExcel(String fileName, List<String> headers, List<Map<String, String>> list){
        OutputStream out = null;
        HSSFWorkbook workbook = null;
        try {
            // 创建一个webbook
            workbook = new HSSFWorkbook();
            // 在webbook中添加一个sheet,并设置名称
            HSSFSheet sheet = workbook.createSheet(fileName);
            // 创建单元格,并设置值表头 设置表头居中
            HSSFCellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            //设置字体样式
            HSSFFont hssfFont = workbook.createFont();
            hssfFont.setFontName("Calibri");
            hssfFont.setFontHeightInPoints((short) 11);//设置字体大小
            hssfFont.setBoldweight(HSSFFont.DEFAULT_CHARSET);

            cellStyle.setFont(hssfFont);//选择需要用到的字体格式
           
            // 在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
            HSSFRow row = sheet.createRow(0);
            HSSFCell cell = null;
            int colsCount = headers.size();//列数
            for (int i = 0; i < colsCount; i++) {
                cell = row.createCell((short) i);
                cell.setCellValue(headers.get(i));
                cell.setCellStyle(cellStyle);
                cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                sheet.setColumnWidth((short)i,(short)7000);
            }

            // 设置内容
            for (int i = 0; i < list.size(); i++) {
                // 创建一个新的rowId行 行对象
                row = sheet.createRow(i+1);
                for (int k = 0; k < colsCount; k++) {
                      cell = row.createCell((short)k);
                      String _value = list.get(i).get(headers.get(k));
                      cell.setCellValue(StringTools.isEmpty(_value)?"":_value);
                      cell.setCellStyle(cellStyle);
                      cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                }
            }

            // 设置Excel名称,格式为名称+时间
            StringBuffer sb = new StringBuffer();
            sb.append(fileName+"-").append(new SimpleDateFormat("yyyyMMdd-hhmmss").format(new Date())).append( ".xls");
            String excelName = sb.toString();

            HttpServletResponse response = ServletActionContext.getResponse();
            HttpServletRequest request = ServletActionContext.getRequest();
            boolean isIE = request.getHeader("User-Agent").indexOf("MSIE") > 0;
            if (isIE) {
                response.setHeader("Content-Disposition", "attachment;filename=" +
                            new String(excelName.getBytes("gb2312"), "ISO-8859-1"));
            } else {
                String filename = new String(excelName.getBytes(), "ISO-8859-1");
                response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            }
            response.setContentType("application/octet-stream");
            out = response.getOutputStream();

            workbook.write(out);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e2) {
                logger.error(e2.getMessage(), e2);
            }
        }
    }

}

你可能感兴趣的:(java,poi,IO,Excel)