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

Java編寫(xiě)通用的導(dǎo)出任何對(duì)象列表數(shù)據(jù)到excel的工具類(lèi)

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

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

1.控制層代碼

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

此處的list可以是任意數(shù)據(jù),也可以是任意SQL組裝的list數(shù)據(jù),標(biāo)題會(huì)以sql的別名為準(zhǔn).

2.CommonExcelUtils工具類(lèi)

    /**
     * 動(dòng)態(tài)列表導(dǎo)出
     * @param response
     * @param list        數(shù)據(jù)list
     * @param sheetName    頁(yè)簽名稱(chēng),也是總標(biāo)題的名稱(chēng)
     * @param fileName    導(dǎo)出文件名
     */
    @SuppressWarnings("all")
    public static String exportDynamicsData(HttpServletResponse response,
            List list, String sheetName, String fileName) throws IOException {
        
        //將list數(shù)據(jù)轉(zhuǎn)成指定類(lèi)型
        List<LinkedHashMap<String, Object>> data = CommonBeanUtils.convertListToMap(list);
        
        List<List> rows = new ArrayList<>();//excel導(dǎo)出整體數(shù)據(jù)
        List<String> titles = new ArrayList<>();//excel導(dǎo)出標(biāo)題(首行)
        List<String> title = new ArrayList<>();
        title.add(sheetName);
        rows.add(title);
        
        //組裝標(biāo)題
         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";//導(dǎo)出文件名稱(chēng)
        
        //聲明一個(gè)工作簿
        XSSFWorkbook workbook = new XSSFWorkbook();
          XSSFSheet sheet = workbook.createSheet(sheetName);
          sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, titles.size()-1));//合并第一行的單元格,作標(biāo)題
          sheet.setDefaultColumnWidth(14);        //設(shè)置表格列寬度
          
          //導(dǎo)出操作
          ExcelUtil.exportExcel(response, rows, workbook, sheet, fileName);
          
          return fileName;
    }

3.CommonBeanUtils工具類(lèi)

    /**
     * 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工具類(lèi)

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>
{
 
    /**
     * 自定義導(dǎo)出
     * @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("宋體");
        //寫(xiě)入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)建一個(gè)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)建一個(gè)單元格
                XSSFCell cell = row.createCell(i);
                //value單元格值
                Object value = data.get(i);
                
                //設(shè)置第一個(gè)行標(biāo)題的樣式
                if(i==0 && rowIndex==1) {
                       cell.setCellStyle(createTitleCellStyle);
                   }
                //設(shè)置表頭樣式
                if(rowIndex==2) {
                    cell.setCellStyle(createTableCellStyle);
                }
                if(rowIndex>2) {
                    //如果是數(shù)字類(lèi)型,則字體向右對(duì)齊
                    if(value instanceof BigDecimal || value instanceof Integer) {
                        row.getCell(i).setCellStyle(rightRowCellStyle);
                    }else {
                        row.getCell(i).setCellStyle(leftRowCellStyle);
                    }
                }
                //將內(nèi)容對(duì)象的文字內(nèi)容寫(xiě)入到單元格中(單獨(dú)處理數(shù)值類(lèi)型)
                if(value instanceof BigDecimal) {
                    BigDecimal v = (BigDecimal)value;
                    cell.setCellValue(v.doubleValue());
                }else {
                    cell.setCellValue(String.valueOf(value));
                }
            }
        }
        //準(zhǔn)備將Excel的輸出流通過(guò)response輸出到頁(yè)面下載
        //八進(jìn)制輸出流
        response.setContentType("application/octet-stream");
        //設(shè)置導(dǎo)出Excel的名稱(chēng)
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        //刷新緩沖
        response.flushBuffer();
        //workbook將Excel寫(xiě)入到response的輸出流中,供頁(yè)面下載該Excel文件
        workbook.write(response.getOutputStream());
 
        //關(guān)閉workbook
        workbook.close();
    }
    
    /**
     * 設(shè)置標(biāo)題單元樣式
     *
     * @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è)置標(biāo)題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設(shè)置列標(biāo)題樣式
        
        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è)置標(biāo)題字體
        cellStyle.setFont(font);
        cellStyle.setWrapText(true);
        cellStyle = workbook.createCellStyle();
        cellStyle.setFont(font);// 設(shè)置列標(biāo)題樣式
        
        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)容單元樣式(字體靠右對(duì)齊)
     * 數(shù)字類(lèi)型
     * @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)容單元樣式(字體靠左對(duì)齊)
     * 文本類(lè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;
     }
}

最終導(dǎo)出效果:

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

相關(guān)文章

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

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

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

    mybatis中嵌套查詢(xún)的使用解讀

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

    SpringBoot依賴(lài)注入的三種方式

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

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

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

    Java集合List的使用詳細(xì)解析

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

    java String類(lèi)常用方法練習(xí)小結(jié)

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

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

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

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

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

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

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

    淺談單例模式和線(xiàn)程安全問(wèn)題

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

最新評(píng)論

扬州市| 衡阳县| 甘孜县| 石河子市| 嘉禾县| 淳安县| 雷波县| 普兰店市| 泸溪县| 罗江县| 静海县| 孙吴县| 仁寿县| 威海市| 合阳县| 安岳县| 微山县| 通榆县| 精河县| 从化市| 定襄县| 建水县| 繁昌县| 宁安市| 双柏县| 运城市| 武宣县| 广平县| 汝南县| 福海县| 绥中县| 邵阳市| 女性| 东平县| 尚志市| 台东县| 大足县| 新绛县| 彭州市| 淮安市| 夹江县|