最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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);        //設置表格列寬度
          
          //導出操作
          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 {                
        //設置單元格字體
        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);
                
                //設置第一個行標題的樣式
                if(i==0 && rowIndex==1) {
                       cell.setCellStyle(createTitleCellStyle);
                   }
                //設置表頭樣式
                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");
        //設置導出Excel的名稱
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //刷新緩沖
        response.flushBuffer();
        //workbook將Excel寫入到response的輸出流中,供頁面下載該Excel文件
        workbook.write(response.getOutputStream());
 
        //關閉workbook
        workbook.close();
    }
    
    /**
     * 設置標題單元樣式
     *
     * @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);// 設置標題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設置列標題樣式
        
        XSSFColor color = new XSSFColor();
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        color.setRGB(intToByteArray(getIntFromColor(255,231,228)));
        //設置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //設置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        
        //設置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        
        return cellStyle;
    }
    
    /**
     * 設置表頭單元樣式
     *
     * @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);// 設置標題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設置列標題樣式
        
        XSSFColor color = new XSSFColor();
        //根據(jù)你需要的rgb值獲取byte數(shù)組
        color.setRGB(intToByteArray(getIntFromColor(251,241,227)));
        //設置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        
        //設置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        
        return cellStyle;
    }
    
    /**
     * 設置內(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)));
        //設置自定義背景顏色
        cellStyle.setFillForegroundColor(color);
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        //設置邊框
        cellStyle.setBorderBottom(BorderStyle.THIN); //下邊框
        cellStyle.setBorderLeft(BorderStyle.THIN);//左邊框
        cellStyle.setBorderTop(BorderStyle.THIN);//上邊框
        cellStyle.setBorderRight(BorderStyle.THIN);//右邊框
        XSSFColor borderColor = new XSSFColor();
        //設置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.CENTER);
        //設置字體垂直居中
        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;
    }
    
    /**
     * 設置內(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);
        
        //設置字體水平居中
        cellStyle.setAlignment(HorizontalAlignment.RIGHT);
        //設置字體垂直居中
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        return cellStyle;
    }
    
    /**
     * 設置內(nèi)容單元樣式(字體靠左對齊)
     * 文本類型
     * @param workbook
     * @return
     */
    public static XSSFCellStyle createLeftRowCellStyle(XSSFWorkbook workbook) {
        XSSFCellStyle cellStyle = workbook.createCellStyle();
        //設置字體位置
        cellStyle.setAlignment(HorizontalAlignment.LEFT);
        //設置字體垂直居中
        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)容,更多關于Java導出列表數(shù)據(jù)的資料請關注腳本之家其它相關文章!

相關文章

  • Spring?boot?easyexcel?實現(xiàn)復合數(shù)據(jù)導出、按模塊導出功能

    Spring?boot?easyexcel?實現(xiàn)復合數(shù)據(jù)導出、按模塊導出功能

    這篇文章主要介紹了Spring?boot?easyexcel?實現(xiàn)復合數(shù)據(jù)導出、按模塊導出,實現(xiàn)思路流程是準備一個導出基礎填充模板,默認填充key,本文給大家介紹的非常詳細,需要的朋友可以參考下
    2023-09-09
  • mybatis中嵌套查詢的使用解讀

    mybatis中嵌套查詢的使用解讀

    這篇文章主要介紹了mybatis中嵌套查詢的使用解讀,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • SpringBoot依賴注入的三種方式

    SpringBoot依賴注入的三種方式

    本文將通過代碼示例詳細介紹SpringBoot依賴注入的三種方式,對學習依賴注入有一定的參考價值,需要的朋友可以參考一下
    2023-04-04
  • Java正則表達式循環(huán)匹配字符串方式

    Java正則表達式循環(huán)匹配字符串方式

    這篇文章主要介紹了Java正則表達式循環(huán)匹配字符串方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Java集合List的使用詳細解析

    Java集合List的使用詳細解析

    這篇文章主要介紹了Java集合List的使用詳細解析,List集合類中元素有序、且可重復,集合中的每個元素都有其對應的順序索引,鑒于Java中數(shù)組用來存儲數(shù)據(jù)的局限性,我們通常使用java.util.List替代數(shù)組,需要的朋友可以參考下
    2023-11-11
  • java String類常用方法練習小結(jié)

    java String類常用方法練習小結(jié)

    本文主要介紹了java String類常用方法的例子,具有很好的參考價值,下面跟著小編一起來看下吧
    2017-02-02
  • JavaSE多線程阻塞隊列實現(xiàn)代碼

    JavaSE多線程阻塞隊列實現(xiàn)代碼

    阻塞隊列是一種線程安全的隊列,可以用于多線程之間的數(shù)據(jù)傳遞和同步,下面這篇文章主要介紹了JavaSE多線程阻塞隊列的相關資料,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2025-12-12
  • java實現(xiàn)俄羅斯方塊游戲

    java實現(xiàn)俄羅斯方塊游戲

    這篇文章主要為大家詳細介紹了java實現(xiàn)俄羅斯方塊游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-02-02
  • SpringBoot lombok(注解@Getter @Setter)詳解

    SpringBoot lombok(注解@Getter @Setter)詳解

    通過使用Lombok庫,SpringBoot應用可以自動化生成常用的方法如setter和getter,顯著降低了代碼冗余并提高了開發(fā)效率,Lombok的@Getter和@Setter注解用于自動生成屬性的訪問和修改方法,而@Data注解則提供了一個全面的解決方案
    2024-11-11
  • 淺談單例模式和線程安全問題

    淺談單例模式和線程安全問題

    這篇文章主要介紹了淺談單例模式和線程安全問題,再某些特殊的情況下,存在一個類僅能用來產(chǎn)生一個唯一對象的必要性,因此需要單例模式,需要的朋友可以參考下
    2023-04-04

最新評論

邻水| 汤阴县| 茶陵县| 喀什市| 监利县| 吐鲁番市| 宁武县| 桂东县| 自贡市| 海城市| 东乌珠穆沁旗| 庆元县| 黄浦区| 石家庄市| 临漳县| 天峻县| 江安县| 美姑县| 五指山市| 会宁县| 石家庄市| 富平县| 社旗县| 姜堰市| 卓尼县| 前郭尔| 咸丰县| 突泉县| 姚安县| 东莞市| 武川县| 奉节县| 乌拉特前旗| 北京市| 汉中市| 调兵山市| 比如县| 瑞安市| 绿春县| 梨树县| 民权县|