后台excel导出(单sheet 多sheet)

//单sheet调用模板
 public void exportInfo(String ids,HttpServletResponse response) {	
        try {
			//单元格列头
			String[] rowName = {"所属单位","隐患描述", "隐患分类", "隐患级别", "隐患状态", "隐患来源"};
			//创建list存数据
			  List<Object[]> dataList = new ArrayList<>();
			  //从数据库中查询出符合条件 要导出的数据
			    List<Hiddendanger> list = new ArrayList<>();
            list = hiddendangerMapper.selectListByParams();
            //开始填充数据
 			 Object[] data = null;
            for (Hiddendanger eduExerciseProblem : list) {
                data = new Object[17];
                // 所属单位
                if (org.apache.commons.lang3.StringUtils.isNotBlank(eduExerciseProblem.getQyname())) {
                    data[0] = eduExerciseProblem.getQyname();
                } else {
                    data[0] = "";
                }
             
                //将数据放入存数据的list中
                dataList.add(data);
            }

			 ExportExcelUtil export = new ExportExcelUtil("隐患信息", rowName, dataList, response);
            String fileName = "隐患信息" + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls";
            export.exportExcel(fileName);
   }
//多sheet调用模板
@Override
    public void peopleAndPostExport(HttpServletResponse response) throws Exception {

        List<Workplace> workplaceList = workplaceMapper.getWorkplaceByQyidAndName(UserUtil.getCurrQyId(), null);
        List<SeUser> userList = userFeign.getUsersByQyId(UserUtil.getCurrQyId()).getData();

        List<List<String>> data = new ArrayList<>();
        List<List<String>> data1 = new ArrayList<>();
        List<List<String>> data2 = new ArrayList<>();
        String[] headers = { "部门", "岗位", "人员姓名", "身份证号"};
        String[] headers1 = { "人员姓名", "身份证号"};
        String[] headers2 = { "部门", "岗位" };
        for(SeUser eduExerciseProblem:userList){
            List<String> list = new ArrayList<>();
            list.add(eduExerciseProblem.getRealname());
            list.add(eduExerciseProblem.getIdcard());
            data1.add(list);
        }

        for(Workplace eduExerciseProblem:workplaceList){
            List<String> list = new ArrayList<>();
            list.add(eduExerciseProblem.getDeptname());
            list.add(eduExerciseProblem.getWorkplace());
            data2.add(list);
        }

        ExportExcelUtil export = new ExportExcelUtil(response);
        HSSFWorkbook workbook = new HSSFWorkbook();
        String fileName = "人员-岗位信息导入模板" + DateFormatUtils.format(new Date(), "yyyy-MM-dd") + ".xls";
        export.exportExcels(workbook, 0, "数据导入页", headers, data);
        export.exportExcels(workbook, 1, "人员信息页", headers1, data1);
        export.exportExcels(workbook, 2, "岗位信息页", headers2, data2);
        OutputStream sos = response.getOutputStream();
        response.setContentType("application/octet-stream");
        // 设置下载文件名
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        // 向客户端输出文件
        workbook.write(sos);
        sos.flush();
        sos.close();
    }
package com.zhjt.utils;


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class ExportExcelUtil {
    // 显示的导出表的标题
    private String title;
    // 导出表的列名
    private String[] firstrowName;
    private String[] rowName;

    private List<Object[]> dataList = new ArrayList<Object[]>();

    HttpServletResponse response;

    // 构造方法,传入要导出的数据
    public ExportExcelUtil(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse res) {
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.response = res;
    }
    public ExportExcelUtil(String title,String[] firstrowName, String[] rowName, List<Object[]> dataList, HttpServletResponse res) {
        this.dataList = dataList;
        this.firstrowName=firstrowName;
        this.rowName = rowName;
        this.title = title;
        this.response = res;
    }

    /**
     *
     * @Title: fhexport
     * @Description: TODO(任务下达汇总复合表导出)
     * @throws Exception
     * @retrun void 返回值
     * @date 2017年8月2日 下午4:48:47
     * @throws
     */
    public void fhexport() throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
        HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

        // 产生表格标题行
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);

        // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
        HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);// 获取列头样式对象
        HSSFCellStyle style = getStyle(workbook); // 单元格样式对象

        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(title);

        // 定义所需列数
        int columnNumFirst=firstrowName.length;
        int columnNum = rowName.length;

        HSSFRow rowRowName=sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
        // 将列头设置到sheet的单元格中
        for (int n = 0; n <=columnNumFirst; n++) {
            HSSFCell cellRowName=null;
            HSSFRichTextString text=null;

            if(n>2){
                cellRowName = rowRowName.createCell((n-1)*2-1); // 创建列头对应个数的单元格
                text = new HSSFRichTextString(firstrowName[n-1]);
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
                cellRowName.setCellValue(text); // 设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式

                cellRowName = rowRowName.createCell((n-1)*2); // 创建列头对应个数的单元格
                text = new HSSFRichTextString(firstrowName[n-1]);
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
                cellRowName.setCellValue(text); // 设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
                sheet.addMergedRegion(new CellRangeAddress(2,2,(n-1)*2-1,(n-1)*2));
            }else{
                cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
                if(n<1){
                    text = new HSSFRichTextString("序号");
                }else{
                    text = new HSSFRichTextString(firstrowName[n-1]);
                }
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
                cellRowName.setCellValue(text); // 设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
            }

        }

        HSSFRow rowRowName2= sheet.createRow(3); // 在索引3的位置创建行(最顶端的行开始的第三行)
        // 将列头设置到sheet的单元格中
        for (int n = 0; n < columnNum; n++) {

            HSSFCell cellRowName = rowRowName2.createCell(n); // 创建列头对应个数的单元格
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
            HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
            cellRowName.setCellValue(text); // 设置列头单元格的值
            cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式

            if(n<3){
                sheet.addMergedRegion(new CellRangeAddress(2,3,n,n));
            }
        }

        // 将查询出的数据设置到sheet对应的单元格中
        int r=1,p=0;
        for (int i = 0; i < dataList.size(); i++) {

            Object[] obj = dataList.get(i);// 遍历每个对象
            HSSFRow row = sheet.createRow(i + 4);// 创建所需的行数

            int l=0;
            for (int j = 0; j < obj.length; j++) {
                HSSFCell cell = null; // 设置单元格的数据类型
                if (j == 0) {
                    cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
                    if (i%5 != 0||i==0){
                        cell.setCellValue(r);
                    }else{
                        r++;
                        cell.setCellValue(r);
                    }
                    cell.setCellStyle(style); // 设置单元格样式

                } else {
                    cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue(obj[j].toString()); // 设置单元格的值
                    cell.setCellStyle(style); // 设置单元格样式

                    if (i%5 == 0&&i!=0){
                        if(j>2){
                            sheet.addMergedRegion(new CellRangeAddress(p*5 + 8,p*5 + 8,j+l,(j-1)*2));
                            l++;
                        }
                    }

                    if(i==dataList.size()-1){
                        if(j>2){
                            sheet.addMergedRegion(new CellRangeAddress(p*5 + 8,p*5 + 8,j+l,(j-1)*2));
                            l++;
                        }
                    }

                }

            }

            if (i%5 == 0&&i!=0){ p++;}
//				if(i==dataList.size()-1){p++;}

            //合并序号和行业
            sheet.addMergedRegion(new CellRangeAddress(i*5+4,i*5 + 8,0,0));
            sheet.addMergedRegion(new CellRangeAddress(i*5+4,i*5 + 8,1,1));
        }

        // 让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                // 当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    currentCell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    String temp = currentCell.getStringCellValue();
                    if(temp!=null&&!"".equals(temp)){
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }

                }
            }
            if (colNum == 0) {
                sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
            } else {
                sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
            }
        }
//			sheet.addMergedRegion(new CellRangeAddress(2,3,0,0));
//			sheet.addMergedRegion(new CellRangeAddress(2,3,1,1));
//			sheet.addMergedRegion(new CellRangeAddress(2,3,2,2));

        OutputStream sos = response.getOutputStream();
        response.setContentType("application/octet-stream");
        // 获取原文件名
        String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
        // 设置下载文件名
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        // 向客户端输出文件
        workbook.write(sos);
        sos.flush();
        sos.close();

    }

    /*
     * 导出数据,数据中的第一列数据将会作为序号,该方法有问题
     */
    public void export() throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
        HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

        // 产生表格标题行
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);

        // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
        HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);// 获取列头样式对象
        HSSFCellStyle style = getStyle(workbook); // 单元格样式对象

        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(title);

        // 定义所需列数
        int columnNum = rowName.length;
        HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

        // 将列头设置到sheet的单元格中
        for (int n = 0; n < columnNum; n++) {
            HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
            HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
            cellRowName.setCellValue(text); // 设置列头单元格的值
            cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
        }

        // 将查询出的数据设置到sheet对应的单元格中
        for (int i = 0; i < dataList.size(); i++) {

            Object[] obj = dataList.get(i);// 遍历每个对象
            HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数

            for (int j = 0; j < obj.length; j++) {
                HSSFCell cell = null; // 设置单元格的数据类型
                if (j == 0) {
                    cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
                    cell.setCellValue(i + 1);
                } else {
                    cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
                    cell.setCellValue((null!=obj[j])?obj[j].toString():""); // 设置单元格的值
                }
                cell.setCellStyle(style); // 设置单元格样式
            }
        }
        // 让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                // 当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    currentCell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    String temp = currentCell.getStringCellValue();
                    if(temp!=null&&!"".equals(temp)){
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }

                }
            }
            if (colNum == 0) {
                sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
            } else {
                sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
            }
        }

        OutputStream sos = response.getOutputStream();
        response.setContentType("application/octet-stream");
        // 获取原文件名
        String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
        // 设置下载文件名
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        // 向客户端输出文件
        workbook.write(sos);
        sos.flush();
        sos.close();

    }

    /**
     *
     * @param sheetName
     * @param titles	表头
     * @param datas	数据,每行对应map中一条记录,统计项为key,表头对应数据放在value的String[]中。
     * @return	HSSFWorkbook
     * @throws IOException
     */
    public static HSSFWorkbook exportExcel(String sheetName,String[] titles, Map<String,String[]> datas) throws IOException{
        int[] columWidth = new int[titles.length+1];
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet(sheetName);

        // 产生表格标题行
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);
        // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
        HSSFCellStyle columnTopStyle = getColumnTopStyle(wb);// 获取列头样式对象
        HSSFCellStyle style = getStyle(wb); // 单元格样式对象
        //设置合并前两行和所有列
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (titles.length)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(sheetName);
        //设置表头行第一列为空
        HSSFRow row = sheet.createRow(2);
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("");
        cell.setCellStyle(style);
        // 定义所需列数
        int columnNum = titles.length;
        for (int i = 0; i < columnNum; i++) {
            HSSFCell cellRowName = row.createCell(i+1); // 创建列头对应个数的单元格
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
            HSSFRichTextString text = new HSSFRichTextString(titles[i]);
            cellRowName.setCellValue(text); // 设置列头单元格的值
            cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
            int length = titles[i].getBytes().length*256;
            sheet.setColumnWidth(i+1, length);
            columWidth[i+1] = length;
        }

        List<String> keys = new LinkedList<String>(datas.keySet());
        for (int i = 0; i < keys.size(); i++) {//map每条记录对应一行
            String key = keys.get(i);//map的key为首列查询内容
            row = sheet.createRow(i + 3);//前两行为标题。第三行为表头
            row.createCell(0).setCellValue(key);
            int length = key.getBytes().length*256;
            if(length>columWidth[0]){
                columWidth[0] = length;
                sheet.setColumnWidth(0, columWidth[0]);
            }

            String[] data = datas.get(key);
            for (int j = 0; j < data.length; j++) {//循环数据并填充单元格
                int length2 = data[j].getBytes().length*300;
                if(length2>columWidth[j+1]){
                    columWidth[j+1] = length2;
                    sheet.setColumnWidth(j+1, columWidth[j+1]);
                }
                cell = row.createCell(j+1);
                cell.setCellValue(data[j]);
                cell.setCellStyle(style); // 设置单元格样式
            }
        }
        return wb;
    }

    /**
     * @Description 生成复数sheet的excel
     * @Param [sheetNames, titless, datas] 各sheet名称集合,各sheet中标题名称集合,各sheet中数据集合
     * @return org.apache.poi.hssf.usermodel.HSSFWorkbook
     **/
    public static HSSFWorkbook exportPluralSheetExcel(List<String> sheetNames,List<String[]> titless, List<List<String[]>> datas) throws IOException{
        HSSFWorkbook wb = new HSSFWorkbook();
        for (int s = 0; s < sheetNames.size(); s++) {
            String sheetName = sheetNames.get(s);
            HSSFSheet sheet = wb.createSheet(sheetName);

            String[] titles = titless.get(s);
            // 产生表格标题行
            int[] columWidth = new int[titles.length];
            HSSFRow rowm = sheet.createRow(0);
            HSSFCell cellTiltle = rowm.createCell(0);
            // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
            HSSFCellStyle columnTopStyle = getColumnTopStyle(wb);// 获取列头样式对象
            HSSFCellStyle style = getStyle(wb); // 单元格样式对象
            //设置合并前两行和所有列
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (titles.length-1)));
            cellTiltle.setCellStyle(columnTopStyle);
            cellTiltle.setCellValue(sheetName);
            //设置表头行第一列为空
            HSSFRow row = sheet.createRow(2);
            HSSFCell cell = row.createCell(0);
            cell.setCellValue("");
            cell.setCellStyle(style);
            // 定义所需列数
            int columnNum = titles.length;
            for (int i = 0; i < columnNum; i++) {
                HSSFCell cellRowName = row.createCell(i); // 创建列头对应个数的单元格
                cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(titles[i]);
                cellRowName.setCellValue(text); // 设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
                int length = titles[i].getBytes().length*256;
                sheet.setColumnWidth(i, length);
                columWidth[i] = length;
            }

            List<String[]> sdata = datas.get(s);
            for (int i = 0; i < sdata.size(); i++) {
                row = sheet.createRow(i + 3);//前两行为标题。第三行为表头
                String[] data = sdata.get(i);
                for (int j = 0; j < data.length; j++) {//循环数据并填充单元格
                    int length2 = data[j].getBytes().length * 300;
                    if (length2 > columWidth[j]) {
                        columWidth[j] = length2;
                        sheet.setColumnWidth(j, columWidth[j]);
                    }
                    cell = row.createCell(j);
                    cell.setCellValue(data[j]);
                    cell.setCellStyle(style); // 设置单元格样式
                }
            }

//            List<String> keys = new LinkedList<String>(datas.keySet());
//            for (int i = 0; i < keys.size(); i++) {//map每条记录对应一行
//                String key = keys.get(i);//map的key为首列查询内容
//                row = sheet.createRow(i + 3);//前两行为标题。第三行为表头
//                row.createCell(0).setCellValue(key);
//                int length = key.getBytes().length*256;
//                if(length>columWidth[0]){
//                    columWidth[0] = length;
//                    sheet.setColumnWidth(0, columWidth[0]);
//                }
//
//                String[] data = datas.get(key);
//                for (int j = 0; j < data.length; j++) {//循环数据并填充单元格
//                    int length2 = data[j].getBytes().length*300;
//                    if(length2>columWidth[j+1]){
//                        columWidth[j+1] = length2;
//                        sheet.setColumnWidth(j+1, columWidth[j+1]);
//                    }
//                    cell = row.createCell(j+1);
//                    cell.setCellValue(data[j]);
//                    cell.setCellStyle(style); // 设置单元格样式
//                }
//            }
        }
        return wb;
    }

    /*
     * 列头单元格样式
     */
    public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {

        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        font.setFontHeightInPoints((short) 11);
        // 字体加粗
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

    /*
     * 列数据信息单元格样式
     */
    public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        // 设置字体大小
        // font.setFontHeightInPoints((short)10);
        // 字体加粗
        // font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 设置字体名字
        font.setFontName("Courier New");
        // 设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置底边框;
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        // 设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.BLACK.index);
        // 设置左边框;
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.BLACK.index);
        // 设置右边框;
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 设置右边框颜色;
        style.setRightBorderColor(HSSFColor.BLACK.index);
        // 设置顶边框;
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.BLACK.index);
        // 在样式用应用设置的字体;
        style.setFont(font);
        // 设置自动换行;
        style.setWrapText(false);
        // 设置水平对齐的样式为居中对齐;
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        return style;

    }

    public static HSSFWorkbook exportExcel(String titleName,String[] columnName, List<Object[]> datas){
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet();
        // 产生表格标题行
        HSSFRow title = sheet.createRow(0);
        HSSFCell cellTitle = title.createCell(0);
        HSSFCellStyle columnTopStyle = getColumnTopStyle(wb);// 获取列头样式对象
        HSSFCellStyle style = getStyle(wb); // 单元格样式对象
        //设置合并前两行和所有列
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, columnName.length));
        cellTitle.setCellStyle(columnTopStyle);
        cellTitle.setCellValue(titleName);
        //设置表头行
        HSSFRow row1 = sheet.createRow(1);
        for(int i=0;i<=columnName.length;++i) {
        	HSSFCell cell = row1.createCell(i);
        	if(i==0) {
        		cell.setCellValue("序号");
        	}else {
        		cell.setCellValue(columnName[i-1]);
        	}        	
            cell.setCellStyle(style);
        }
        //数据填充部分
        for(int i=0;i<datas.size();++i) {
        	 HSSFRow row = sheet.createRow(i+2);
        	 for(int j=0;j<=columnName.length;++j) {
        		 HSSFCell cell = row.createCell(j);
        		 if(j==0) {
             		cell.setCellValue(i+1);
             	 }else {
             		cell.setCellValue(datas.get(i)[j-1]==null?"":datas.get(i)[j-1].toString());
             	 }
        		 cell.setCellStyle(style);
        	 }
        }
        return wb;
    }

    public void exportExcel(String fileName) throws Exception {
        HSSFWorkbook workbook = new HSSFWorkbook(); // 创建工作簿对象
        HSSFSheet sheet = workbook.createSheet(title); // 创建工作表

        // 产生表格标题行
        HSSFRow rowm = sheet.createRow(0);
        HSSFCell cellTiltle = rowm.createCell(0);

        // sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
        HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);// 获取列头样式对象
        HSSFCellStyle style = getStyle(workbook); // 单元格样式对象

        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length - 1)));
        cellTiltle.setCellStyle(columnTopStyle);
        cellTiltle.setCellValue(title);

        // 定义所需列数
        int columnNum = rowName.length;
        HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)

        // 将列头设置到sheet的单元格中
        for (int n = 0; n < columnNum; n++) {
            HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
            cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
            HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
            cellRowName.setCellValue(text); // 设置列头单元格的值
            cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
        }

        // 将查询出的数据设置到sheet对应的单元格中
        for (int i = 0; i < dataList.size(); i++) {

            Object[] obj = dataList.get(i);// 遍历每个对象
            HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数

            for (int j = 0; j < obj.length; j++) {
                HSSFCell cell = null; // 设置单元格的数据类型
                cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
                if(obj[j] != null)
                    cell.setCellValue(obj[j].toString()); // 设置单元格的值
                else
                    cell.setCellValue("");
                cell.setCellStyle(style); // 设置单元格样式
            }
        }
        // 让列宽随着导出的列长自动适应
        for (int colNum = 0; colNum < columnNum; colNum++) {
            int columnWidth = sheet.getColumnWidth(colNum) / 256;
            for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
                HSSFRow currentRow;
                // 当前行未被使用过
                if (sheet.getRow(rowNum) == null) {
                    currentRow = sheet.createRow(rowNum);
                } else {
                    currentRow = sheet.getRow(rowNum);
                }
                if (currentRow.getCell(colNum) != null) {
                    HSSFCell currentCell = currentRow.getCell(colNum);
                    currentCell.setCellType(HSSFCell.CELL_TYPE_STRING);
                    String temp = currentCell.getStringCellValue();
                    if(temp!=null&&!"".equals(temp)){
                        int length = currentCell.getStringCellValue().getBytes().length;
                        if (columnWidth < length) {
                            columnWidth = length;
                        }
                    }

                }
            }
            try {
                if (colNum == 0) {
                    sheet.setColumnWidth(colNum, (columnWidth - 2) * 256);
                } else {
                    sheet.setColumnWidth(colNum, (columnWidth + 4) * 256);
                }
            } catch (IllegalArgumentException e) {
                sheet.setColumnWidth(colNum, 65280);
            }
        }

        OutputStream sos = response.getOutputStream();
        response.setContentType("application/octet-stream");
        // 获取原文件名
        //String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
        // 设置下载文件名
        response.addHeader("Content-Disposition",
                "attachment; filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        // 向客户端输出文件
        workbook.write(sos);
        sos.flush();
        sos.close();
    }

  /**
     * @Description: 导出Excel 包含多张sheet
     * @author wang
     * @param workbook
     * @param sheetNum (sheet的位置,0表示第一个表格中的第一个sheet)
     * @param sheetTitle  (sheet的名称)
     * @param headers    (表格的列标题)
     * @param result   (表格的数据)
     * @throws Exception
     */
    public void exportExcels(HSSFWorkbook workbook, int sheetNum,
                            String sheetTitle, String[] headers, List<List<String>> result) throws Exception {
        // 生成一个表格
        HSSFSheet sheet = workbook.createSheet();
        workbook.setSheetName(sheetNum, sheetTitle);
        // 设置表格默认列宽度为20个字节
        sheet.setDefaultColumnWidth((short) 20);
        // 生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        // 设置这些样式
        style.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 生成一个字体
        HSSFFont font = workbook.createFont();
        font.setColor(HSSFColor.BLACK.index);
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // 把字体应用到当前的样式
        style.setFont(font);

        // 指定当单元格内容显示不下时自动换行
        style.setWrapText(true);

        // 产生表格标题行
        HSSFRow row = sheet.createRow(0);
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = row.createCell((short) i);

            cell.setCellStyle(style);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text.toString());
        }
        // 遍历集合数据,产生数据行
        if (result != null) {
            Integer index = 1;
            for (List<String> m : result) {
                row = sheet.createRow(index);
                int cellIndex = 0;
                for (String str : m) {
                    HSSFCell cell = row.createCell((short) cellIndex);
                    if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
                        cell.setCellValue(str.toString());
                    }else {
                        cell.setCellValue("");
                    }

                    cellIndex++;
                }
                index++;
            }
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值