导出excel工具类和依赖

依赖

      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi</artifactId>
          <version>4.0.1</version>
      </dependency>

      <!--支持07年之前的-->
      <dependency>
          <groupId>org.apache.poi</groupId>
          <artifactId>poi-ooxml</artifactId>
          <version>4.0.1</version>
      </dependency>

工具类

package com.xy.xuld.utils;

import com.xy.xuld.modules.vo.ExcelData;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.extensions.XSSFCellBorder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Dell on 2019/5/10.
 */
public class ExcelUtils {

    private static Logger logger= LoggerFactory.getLogger(ExcelUtils.class);

    public static void exportExcel(ExcelData data, HttpServletResponse response) throws Exception {
        XSSFWorkbook wb = new XSSFWorkbook();
        try {
            String sheetName = data.getName();
            if (null == sheetName) {
                sheetName = "Sheet1";
            }
            XSSFSheet sheet = wb.createSheet(sheetName);
            writeExcel(wb, sheet, data);
            String fileName=data.getName()+"("+DateUtil.convertDate2String("yyyyMMddHHmmssSSS",new Date())+")"+".xlsx";
            fileName = URLEncoder.encode(fileName, "utf-8");
            // 告诉浏览器用什么软件可以打开此文件 
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition","attachment;filename="+fileName+"");
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch(Exception e){
            e.printStackTrace();
        }finally{
            //此处需要关闭 wb 变量
            wb.close();
        }
    }

    private static void writeExcel(XSSFWorkbook wb, Sheet sheet, ExcelData data) {

        int rowIndex = 0;

        rowIndex = writeTitlesToExcel(wb, sheet, data.getTitles());
        try {
            writeRowsToExcel(wb, sheet, data.getRows(), rowIndex,data.getTitles());
        } catch (IOException e) {
            e.printStackTrace();
        }
        autoSizeColumns(sheet, data.getTitles().size() + 1);

    }

    //标题
    private static int writeTitlesToExcel(XSSFWorkbook wb, Sheet sheet,List<String> titles) {
        //行
        int rowIndex = 0;
        //列
        int colIndex = 0;
        Font titleFont = wb.createFont();
        titleFont.setFontName("微软雅黑");
        //titleFont.setBoldweight(Short.MAX_VALUE);
        // titleFont.setFontHeightInPoints((short) 14);
        titleFont.setColor(IndexedColors.BLACK.index);

        XSSFCellStyle titleStyle = wb.createCellStyle();
        titleStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
        titleStyle.setRightBorderColor(IndexedColors.GOLD.getIndex());//边框颜色
        titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
        titleStyle.setBorderTop(BorderStyle.THIN);//上边框
        titleStyle.setBorderRight(BorderStyle.THIN);//右边框
        //THIN 正常 THICK 加粗 DOUBLE两条 DASH_DOT虚线
        /*titleStyle.setFillForegroundColor(new XSSFColor(new Color(182, 184, 192)));
        titleStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/
        titleStyle.setFont(titleFont);
        titleStyle.setWrapText(true);//设置自动换行
//        titleStyle.setFillForegroundColor(IndexedColors.RED.index);
//        setBorder(titleStyle, BorderStyle.THIN, new XSSFColor(new Color(0, 0, 0)));




        Row titleRow = sheet.createRow(rowIndex);

        //====添加一个标题======
        //设置标题样式
        XSSFCellStyle titleStyle2 = wb.createCellStyle();
        titleStyle2.setAlignment(HorizontalAlignment.CENTER);//水平居中
        titleStyle2.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        Font titleFont2 = wb.createFont();
        titleFont2.setFontName("微软雅黑");
        //titleFont.setBoldweight(Short.MAX_VALUE);
        titleFont2.setFontHeightInPoints((short) 18);
        titleFont2.setColor(IndexedColors.BLACK.index);
        titleStyle2.setFont(titleFont2);


        Cell cell2 = titleRow.createCell(0);
        cell2.setCellValue(sheet.getSheetName());
        cell2.setCellStyle(titleStyle2);
        //合并单元格参数分别代表 起始行,截至行,起始列, 截至列
        sheet.addMergedRegion(new CellRangeAddress(rowIndex, ++rowIndex, 0,titles.size()-1));
        rowIndex++;
        //======结束=======

        //====添加一个二级标题======
        //设置样式
        XSSFCellStyle titleStyle3 = wb.createCellStyle();
        titleStyle3.setAlignment(HorizontalAlignment.LEFT);//水平居中
        titleStyle3.setFont(titleFont);
        titleRow = sheet.createRow(rowIndex);
        Cell cell3 = titleRow.createCell(0);
        cell3.setCellValue("创建时间:"+new SimpleDateFormat("yyyy.MM.dd").format(new Date()));
        cell3.setCellStyle(titleStyle3);
        if(titles.size()==1){
            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0,1));
        }else {

            sheet.addMergedRegion(new CellRangeAddress(rowIndex, rowIndex, 0,titles.size()-1));
        }
        rowIndex++;
        //======结束=======

        //重新定位所在行
        titleRow = sheet.createRow(rowIndex);
        // titleRow.setHeightInPoints(25);
        colIndex = 0;
//        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0,titles.size()-1));
        for (String field : titles) {
            Cell cell = titleRow.createCell(colIndex);
            cell.setCellValue(field);
            cell.setCellStyle(titleStyle);
            colIndex++;
        }

        rowIndex++;
        return rowIndex;
    }

    //内容
    private static int writeRowsToExcel(XSSFWorkbook wb, Sheet sheet, List<List<Object>> rows, int rowIndex,List<String> titles) throws IOException {
        int colIndex = 0;
        Font dataFont = wb.createFont();
        dataFont.setFontName("微软雅黑");
        // dataFont.setFontHeightInPoints((short) 14);
        dataFont.setColor(IndexedColors.BLACK.index);
        int flag=0;
        for (int i = 0; i < titles.size(); i++) {
            if(titles.get(i).contains("图片")){
                flag=i;
                break;
            }
        }

        XSSFCellStyle dataStyle = wb.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
        dataStyle.setFont(dataFont);
        int i=0;
        for (List<Object> rowData : rows) {
            Row dataRow = sheet.createRow(rowIndex);
            dataRow.setHeightInPoints(50);
            colIndex = 0;

            for (Object cellData : rowData) {
                Cell cell = dataRow.createCell(colIndex);
                if (cellData != null) {
                   if(colIndex==flag&&cellData.toString().contains("http://")){
                       cell.setCellValue("");
                        try {
                            Drawing drawing = sheet.createDrawingPatriarch();
                            CreationHelper helper = wb.getCreationHelper();
                            URL url = new URL(cellData.toString());
                            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                            boolean notfind =false;
                            try {
                                urlConnection.setConnectTimeout(300);
                                urlConnection.setReadTimeout(1000);
                            if(urlConnection.getResponseCode()>=400){
                                notfind =true;
                            }}catch (Exception e) {
                                notfind =true;
                            }
                            if (!notfind) {
                                InputStream is = new BufferedInputStream(url.openStream());
                                byte[] bytes = IOUtils.toByteArray(is);
                                int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
                                is.close();
                                ClientAnchor anchor = helper.createClientAnchor();
                                anchor.setDx1(0);
                                anchor.setDy1(0);
                                anchor.setDx2(0);
                                anchor.setDy2(0);
                                anchor.setCol1(flag);
                                anchor.setRow1(4+i);
                                anchor.setCol2(flag+1);
                                anchor.setRow2(5+i);
                                Picture pict = drawing.createPicture(anchor, pictureIdx);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                            logger.error("图片未找到");
                        }

                    }
                    else {
                        cell.setCellValue(cellData.toString());
                    }



                } else {
                    cell.setCellValue("");
                }

                cell.setCellStyle(dataStyle);
                colIndex++;
            }
            i++;
            rowIndex++;
        }
        return rowIndex;
    }

    private static void autoSizeColumns(Sheet sheet, int columnNumber) {

        for (int i = 0; i < columnNumber; i++) {
            int orgWidth = sheet.getColumnWidth(i);
            sheet.autoSizeColumn(i, true);
            int newWidth = (int) (sheet.getColumnWidth(i) + 100);
            if(newWidth<255*256){
                sheet.setColumnWidth(i, newWidth < 3000 ? 3000 : newWidth);
            }else{
                sheet.setColumnWidth(i,6000 );
            }
            /*if (newWidth > orgWidth) {
                sheet.setColumnWidth(i, newWidth);
            } else {
                sheet.setColumnWidth(i, orgWidth);
            }*/
        }
    }

    private static void setBorder(XSSFCellStyle style, BorderStyle border, XSSFColor color) {
        style.setBorderTop(border);
        style.setBorderLeft(border);
        style.setBorderRight(border);
        style.setBorderBottom(border);
        style.setBorderColor(XSSFCellBorder.BorderSide.TOP, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.LEFT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.RIGHT, color);
        style.setBorderColor(XSSFCellBorder.BorderSide.BOTTOM, color);
    }
    
}

你可能感兴趣的:(java)