欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java編寫通用的導出任何對象列表數(shù)據(jù)到excel的工具類

 更新時間:2024年12月26日 09:39:00   作者:B1nnnn丶  
在工作中經(jīng)常會遇到列表數(shù)據(jù)的導出,每次需要的時候都要去開發(fā)一次,且數(shù)據(jù)不斷在變化,所以本文將利用Java編寫一個工具類可以導出任何對象列表數(shù)據(jù)到excel,希望對大家有所幫助

在工作中經(jīng)常會遇到列表數(shù)據(jù)的導出,每次需要的時候都要去開發(fā)一次,且數(shù)據(jù)不斷在變化,于是就有了下述的工具類,可傳入各種實體對象的List,最終以指定格式導出excel,廢話不多說,上代碼~

1.控制層代碼

    @PostMapping("/test")
    public void test(HttpServletResponse response) throws Exception {
        
        //查詢?nèi)我鈹?shù)據(jù)列表
        List<ErrorLog> list = errorLogService.selectListByInfo();
        
        //導出操作
        CommonExcelUtils.exportDynamicsData(response, list, "日志", "日志數(shù)據(jù)");
    }

此處的list可以是任意數(shù)據(jù),也可以是任意SQL組裝的list數(shù)據(jù),標題會以sql的別名為準.

2.CommonExcelUtils工具類

    /**
     * 動態(tài)列表導出
     * @param response
     * @param list        數(shù)據(jù)list
     * @param sheetName    頁簽名稱,也是總標題的名稱
     * @param fileName    導出文件名
     */
    @SuppressWarnings("all")
    public static String exportDynamicsData(HttpServletResponse response,
            List list, String sheetName, String fileName) throws IOException {
        
        //將list數(shù)據(jù)轉(zhuǎn)成指定類型
        List<LinkedHashMap<String, Object>> data = CommonBeanUtils.convertListToMap(list);
        
        List<List> rows = new ArrayList<>();//excel導出整體數(shù)據(jù)
        List<String> titles = new ArrayList<>();//excel導出標題(首行)
        List<String> title = new ArrayList<>();
        title.add(sheetName);
        rows.add(title);
        
        //組裝標題
         LinkedHashMap<String,Object> m = (LinkedHashMap<String,Object>) data.get(0);
         Set<String> keySet = m.keySet();
          for (String t : keySet) {
              titles.add(t);
        }
        rows.add(titles);
        
        //組裝數(shù)據(jù)
        for (LinkedHashMap<String,Object> info : data) {
            List d = new ArrayList<>();
            Set<Entry<String, Object>> entrySet = info.entrySet();
            for (Entry<String, Object> da : entrySet) {
                d.add(da.getValue());
            }
            rows.add(d);
        }
        fileName = fileName +"-"+ DateUtils.parseDateToStr("yyMMdd", new Date()) +".xlsx";//導出文件名稱
        
        //聲明一個工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
          XSSFSheet sheet = workbook.createSheet(sheetName);
          sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titles.size()-1));//合并第一行的單元格,作標題
          sheet.setDefaultColumnWidth(14);        //設(shè)置表格列寬度
          
          //導出操作
          ExcelUtil.exportExcel(response, rows, workbook, sheet, fileName);
          
          return fileName;
    }

3.CommonBeanUtils工具類

    /**
     * List轉(zhuǎn)Map
     * @param <T>
     * @param list
     * @return
     */
    public static <T> List<LinkedHashMap<String, Object>> convertListToMap(List<T> list) {
        return list.stream()
            .map(CommonBeanUtils::objectToMap)
            .collect(Collectors.toList());
    }
 
    /**
     * object 轉(zhuǎn) Map
     * @param <T>
     * @param object
     * @return
     */
    private static <T> LinkedHashMap<String, Object> objectToMap(T object) {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for (Field field : object.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            try {
                map.put(field.getName(), field.get(object));
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return map;
    }

4.ExcelUtil工具類

import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
public class ExcelUtil<T>
{
 
    /**
     * 自定義導出
     * @param response
     * @param excelData
     * @param sheetName
     * @param fileName
     * @param columnWidth
     * @throws IOException
     */
    public static void exportExcel(HttpServletResponse response,List<List> excelData,XSSFWorkbook workbook, XSSFSheet sheet,String fileName) throws IOException {                
        //設(shè)置單元格字體
        XSSFFont fontName = workbook.createFont();
        fontName.setFontName("宋體");
        //寫入List<List<String>>中的數(shù)據(jù)
        int rowIndex = 0;
        int rowFlag = -2;
        XSSFCellStyle createTitleCellStyle = createTitleCellStyle(workbook);
        XSSFCellStyle createTableCellStyle = createTableCellStyle(workbook);
        XSSFCellStyle rightRowCellStyle = createRightRowCellStyle(workbook);
        XSSFCellStyle leftRowCellStyle = createLeftRowCellStyle(workbook);
       
        for(List data : excelData){
            if(rowFlag == 8) rowFlag = 0;
            rowFlag++;
            //創(chuàng)建一個row行,然后自增1
            XSSFRow row = sheet.createRow(rowIndex++);
            if(rowIndex==1) row.setHeight((short)(20*30));
            
            //遍歷添加本行數(shù)據(jù)
            for (int i = 0; i < data.size(); i++) {
                //創(chuàng)建一個單元格
                XSSFCell cell = row.createCell(i);
                //value單元格值
                Object value = data.get(i);
                
                //設(shè)置第一個行標題的樣式
                if(i==0 && rowIndex==1) {
                       cell.setCellStyle(createTitleCellStyle);
                   }
                //設(shè)置表頭樣式
                if(rowIndex==2) {
                    cell.setCellStyle(createTableCellStyle);
                }
                if(rowIndex>2) {
                    //如果是數(shù)字類型,則字體向右對齊
                    if(value instanceof BigDecimal || value instanceof Integer) {
                        row.getCell(i).setCellStyle(rightRowCellStyle);
                    }else {
                        row.getCell(i).setCellStyle(leftRowCellStyle);
                    }
                }
                //將內(nèi)容對象的文字內(nèi)容寫入到單元格中(單獨處理數(shù)值類型)
                if(value instanceof BigDecimal) {
                    BigDecimal v = (BigDecimal)value;
                    cell.setCellValue(v.doubleValue());
                }else {
                    cell.setCellValue(String.valueOf(value));
                }
            }
        }
        //準備將Excel的輸出流通過response輸出到頁面下載
        //八進制輸出流
        response.setContentType("application/octet-stream");
        //設(shè)置導出Excel的名稱
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //刷新緩沖
        response.flushBuffer();
        //workbook將Excel寫入到response的輸出流中,供頁面下載該Excel文件
        workbook.write(response.getOutputStream());
 
        //關(guān)閉workbook
        workbook.close();
    }
    
    /**
     * 設(shè)置標題單元樣式
     *
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createTitleCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle  cellStyle = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setBold(true);
        font.setFontHeightInPoints((short) 20);
        font.setFontName(HSSFFont.FONT_ARIAL);// 設(shè)置標題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設(shè)置列標題樣式
        
        XSSFColor color = new XSSFColor();
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        color.setRGB(intToByteArray(getIntFromColor(255,231,228)));
        //設(shè)置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設(shè)置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //設(shè)置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        
        //設(shè)置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        
        return cellStyle;
    }
    
    /**
     * 設(shè)置表頭單元樣式
     *
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createTableCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        XSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        font.setFontName(HSSFFont.FONT_ARIAL);// 設(shè)置標題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設(shè)置列標題樣式
        
        XSSFColor color = new XSSFColor();
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        color.setRGB(intToByteArray(getIntFromColor(251,241,227)));
        //設(shè)置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設(shè)置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        
        //設(shè)置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        
        return cellStyle;
    }
    
    /**
     * 設(shè)置內(nèi)容單元樣式
     *
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createRowCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
 
        XSSFColor color = new XSSFColor();
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        color.setRGB(intToByteArray(getIntFromColor(220,220,220)));
        //設(shè)置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設(shè)置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        XSSFColor borderColor = new XSSFColor();
        //設(shè)置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //設(shè)置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        borderColor.setRGB(intToByteArray(getIntFromColor(181,181,181)));
        cellStyle.setLeftBorderColor(borderColor);
        cellStyle.setRightBorderColor(borderColor);
        cellStyle.setBottomBorderColor(borderColor);
        cellStyle.setTopBorderColor(borderColor);
        
        return cellStyle;
    }
    
    /**
     * 設(shè)置內(nèi)容單元樣式(字體靠右對齊)
     * 數(shù)字類型
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createRightRowCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle  cellStyle = workbook.createCellStyle();
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        
        XSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 11);
        cellStyle.setFont(font);
        
        //設(shè)置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.RIGHT);
        //設(shè)置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }
    
    /**
     * 設(shè)置內(nèi)容單元樣式(字體靠左對齊)
     * 文本類型
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createLeftRowCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        //設(shè)置字體位置
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        //設(shè)置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }
    
    /**
     * rgb轉(zhuǎn)int
     */
     private static int getIntFromColor(int Red, int Green, int Blue){
         Red = (Red << 16) & 0x00FF0000;
         Green = (Green << 8) & 0x0000FF00;
         Blue = Blue & 0x000000FF;
         return 0xFF000000 | Red | Green | Blue;
     }
     
     /**
      * int轉(zhuǎn)byte[]
      */
     public static byte[] intToByteArray(int i) {
         byte[] result = new byte[4];
         result[0] = (byte)((i >> 24) & 0xFF);
         result[1] = (byte)((i >> 16) & 0xFF);
         result[2] = (byte)((i >> 8) & 0xFF);
         result[3] = (byte)(i & 0xFF);
         return result;
     }
}

最終導出效果:

以上就是Java編寫通用的導出任何對象列表數(shù)據(jù)到excel的工具類的詳細內(nèi)容,更多關(guān)于Java導出列表數(shù)據(jù)的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java實現(xiàn)4種微信搶紅包算法(小結(jié))

    Java實現(xiàn)4種微信搶紅包算法(小結(jié))

    微信紅包是大家經(jīng)常使用的,到現(xiàn)在為止仍然有很多紅包開發(fā)的需求,實現(xiàn)搶紅包算法也是面試??碱},本文就詳細的來介紹一下如何實現(xiàn),感興趣的可以了解一下
    2021-12-12
  • Spring Boot異常處理靜止trace

    Spring Boot異常處理靜止trace

    這篇文章主要介紹了Spring Boot異常處理靜止trace,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • 基于SPRINGBOOT配置文件占位符過程解析

    基于SPRINGBOOT配置文件占位符過程解析

    這篇文章主要介紹了基于SPRINGBOOT配置文件占位符過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2019-12-12
  • SpringBoot使用JUL實現(xiàn)日志記錄功能

    SpringBoot使用JUL實現(xiàn)日志記錄功能

    在SpringBoot中,我們可以使用多種日志框架進行日志記錄,其中,JUL(Java Util Logging)是Java平臺自帶的日志框架,它提供了簡單的 API 和配置,可以輕松地進行日志記錄,本文將介紹如何在 SpringBoot中使用JUL進行日志記錄,并提供示例代碼
    2023-06-06
  • Java框架篇:Spring+SpringMVC+hibernate整合開發(fā)

    Java框架篇:Spring+SpringMVC+hibernate整合開發(fā)

    本篇文章將會對Spring+SpringMVC+hibernate的整合開發(fā)進行介紹。具有很好的參考價值。下面跟著小編一起來看下吧
    2017-02-02
  • java+io+swing實現(xiàn)學生信息管理系統(tǒng)

    java+io+swing實現(xiàn)學生信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了java+io+swing實現(xiàn)學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-07-07
  • SpringBoot3+graalvm:整合并打包為可執(zhí)行文件方式

    SpringBoot3+graalvm:整合并打包為可執(zhí)行文件方式

    本文介紹了如何在Spring Boot 3中整合GraalVM,并將其打包為可執(zhí)行文件,適用于Windows和Linux系統(tǒng),通過安裝GraalVM、配置環(huán)境變量、下載Visual Studio組件(僅限Windows)以及使用Maven容器(適用于Linux),可以實現(xiàn)高效的打包和運行
    2024-12-12
  • 時間中間鍵的整理

    時間中間鍵的整理

    這篇文章主要介紹了時間中間鍵的整理的相關(guān)資料,如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,需要的朋友可以參考下
    2017-10-10
  • mybatis plus動態(tài)數(shù)據(jù)源切換及查詢過程淺析

    mybatis plus動態(tài)數(shù)據(jù)源切換及查詢過程淺析

    這篇文章主要介紹了mybatis plus動態(tài)數(shù)據(jù)源切換及查詢過程淺析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2020-12-12
  • @RequestParam使用defaultValue屬性設(shè)置默認值的操作

    @RequestParam使用defaultValue屬性設(shè)置默認值的操作

    這篇文章主要介紹了@RequestParam使用defaultValue屬性設(shè)置默認值的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2021-02-02

最新評論