excel導出工具類(POI)

import com.hikvision.hikadmin.util.DateUtil;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.List;

/**
 * @Description excel導出
 */
public class ExportExcel {

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

    /**
     * excel導出
     *
     * @param excelName excel名稱
     * @param titels    每列標題
     * @param fields    標題所對應實體類中的字段
     * @param data      數據(泛型是對應的實體類)
     * @param response
     */
    public static void export(String excelName, String[] titels, String[] fields, List<?> data, HttpServletResponse response) {

        if (titels.length == 0 || fields.length == 0) return;

        OutputStream os = null;

        response.setContentType("application/x-excel;charset=UTF-8");

        try {

            response.setHeader("Content-disposition", "attachment; filename=" + new String(excelName.getBytes("gb2312"), "ISO8859-1")
                    + DateUtil.formatDate(new Date(), "yyyyMMddHHmmss") + ".xlsx");

            os = response.getOutputStream();
            XSSFWorkbook workBook = new XSSFWorkbook();

            Sheet sheet = workBook.createSheet(excelName);

            Row row = sheet.createRow(0);

            Font f = workBook.createFont();
            f.setBoldweight(Font.BOLDWEIGHT_BOLD);//字體加粗
            f.setFontHeightInPoints((short) 13);//字體大小

            //樣式
            CellStyle style = workBook.createCellStyle();
            style.setAlignment(CellStyle.ALIGN_CENTER);//左右居中
            style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);//上下居中
            style.setFont(f);

            for (int i = 0; i < titels.length; i++) {

                row.createCell(i).setCellValue(titels[i]);

                row.getCell(i).setCellStyle(style);

                sheet.setColumnWidth(i, titels[i].getBytes().length * 2 * 256);
            }


            for (int i = 0; i < data.size(); i++) {

                Row r = sheet.createRow(i + 1);

                Object object = data.get(i);

                for (int j = 0; j < fields.length; j++) {

                    char[] chars = fields[j].toCharArray();

                    //判斷首字母是否小寫
                    if (Character.isLowerCase(chars[0])){
                        chars[0] -= 32;
                    }

                    Method m = object.getClass().getMethod("get" + String.valueOf(chars));

                    r.createCell(j).setCellValue(null == m.invoke(object) ? "" : String.valueOf(m.invoke(object)));

                }
            }

            workBook.write(os);

        } catch (Exception e) {
            logger.error("Excel導出" + excelName + "失敗 : " + e);
        } finally {
            if (os != null) {
                try {
                    os.flush();
                } catch (IOException e) {
                    logger.error("Excel導出" + excelName + "失敗,強制清除輸出流失敗 : " + e);
                }
                IOUtils.closeQuietly(os);
            }
        }

    }

}
相關文章
相關標籤/搜索