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

java實(shí)現(xiàn)把對(duì)象數(shù)組通過(guò)excel方式導(dǎo)出的功能

 更新時(shí)間:2017年03月28日 10:44:47   作者:小明快點(diǎn)跑  
本文主要介紹了java實(shí)現(xiàn)把對(duì)象數(shù)組通過(guò)excel方式導(dǎo)出的功能的相關(guān)知識(shí)。具有很好的參考價(jià)值,下面跟著小編一起來(lái)看下吧

一、導(dǎo)入相關(guān)jar包,pom依賴如下:

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

二、開(kāi)始擼代碼

1.如果導(dǎo)出功能使用的比較多,可以將其做成一個(gè)工具類,對(duì)我下面貼出的代碼進(jìn)行改造

//結(jié)果返回的是寫入的記錄數(shù)(以下用的是自己業(yè)務(wù)場(chǎng)景數(shù)據(jù))
  public int downLoadToExcel(OutputStream outputStream,List<PaimaiMoneyVO> paimaiMoneyVOList) {
     //文檔對(duì)象
  HSSFWorkbook wb = new HSSFWorkbook();
  int rowNum = 0;
  Sheet sheet = wb.createSheet("excel的標(biāo)題");
  Row row0 = sheet.createRow(rowNum++);
    //因?yàn)閳?chǎng)景不同,titil不同,可以在外面寫成數(shù)組當(dāng)參數(shù)傳進(jìn)來(lái)
  row0.createCell(0).setCellValue("第一列屬性名");
  row0.createCell(1).setCellValue("第二列屬性名");
  row0.createCell(2).setCellValue("第三列屬性名");
  row0.createCell(3).setCellValue("第四列屬性名");
  row0.createCell(4).setCellValue("第五列屬性名");
  row0.createCell(5).setCellValue("第六列屬性名");
     if (paimaiMoneyVOList != null && paimaiMoneyVOList.size() > 0) {
   for (PaimaiMoneyVO paimaiMoneyVO : paimaiMoneyVOList) {
    Row row = sheet.createRow(rowNum++);
    row.createCell(0).setCellValue(paimaiMoneyVO.getPaimaiId());
    row.createCell(1).setCellValue(paimaiMoneyVO.getTitle());
    row.createCell(2).setCellValue(paimaiMoneyVO.getUsername());
    row.createCell(3).setCellValue(paimaiMoneyVO.getMoney()+"元");
    row.createCell(4).setCellValue("升價(jià)拍"); 
    row.createCell(5).setCellValue(bidder);
   }
  }
  try {
   wb.write(outputStream);
   LogEnum.LAW_WARE.info("表數(shù)據(jù)寫入到excel表成功,一共寫入了"+(rowNum - 1)+"條數(shù)據(jù)");
   outputStream.close();
  } catch (IOException e) {
   LogEnum.LAW_WARE.error("流關(guān)閉異常!", e);
  } finally {
   if (outputStream != null) {
    try {
     outputStream.close();
    } catch (IOException e) {
     LogEnum.LAW_WARE.error("流關(guān)閉異常!", e);
    }
   }
  }
  return rowNum - 1;
 }

2.“工具類”寫好后,下面就開(kāi)始使用它了,從上面的函數(shù)參數(shù)可以看到,我們需要傳過(guò)去兩個(gè)對(duì)象,一個(gè)是輸出流OutPutStream,通過(guò)流的方式把excel想要到瀏覽器,

另外一個(gè)就是我們需要導(dǎo)出的對(duì)象數(shù)組,好了,不解釋太多,看代碼。(下面的方法寫在action層,通過(guò)struts.xml配置訪問(wèn)即可實(shí)現(xiàn)下載)

public void exportBail(){
  this.fileName = "excel文件名";
  try {
   List<PaimaiMoneyVO> paimaiMoneyVOList = new ArrayList<>();
      //下面是我的業(yè)務(wù)場(chǎng)景獲取對(duì)象數(shù)組
   if(paimaiMoneySearchParam!=null){
    paimaiMoneySearchParam.setVendorId(WebHelper.getVenderId());
    paimaiMoneySearchParam.setPageSize(Constants.AUCTION_WARE_PAGE_SIZE);
    paimaiMoneySearchParam.setPage(page);
    PaimaiMoneyDto paimaiMoneyDto = auctionWareService1.searchPopPaimaiMoneyList(paimaiMoneySearchParam);
    if(paimaiMoneyDto!=null){
     int count = paimaiMoneyDto.getCount();
     int totalPage = count/ Constants.AUCTION_WARE_PAGE_SIZE + (count% Constants.AUCTION_WARE_PAGE_SIZE > 0?1:0);
     for(int i=1;i<=totalPage;i++){
      paimaiMoneySearchParam.setPage(i);
      PaimaiMoneyDto paimaiMoneyResultResult = auctionWareService1.searchPopPaimaiMoneyList(paimaiMoneySearchParam);
      if(paimaiMoneyResultResult!=null){
       paimaiMoneyVOList.addAll(paimaiMoneyResultResult.getList());
      }
     }
    }
   }
   OutputStream outputStream = response.getOutputStream();
   response.reset();//清空輸出流
   //下面是對(duì)中文文件名的處理
   response.setCharacterEncoding("UTF-8");//設(shè)置相應(yīng)內(nèi)容的編碼格式
       //解析瀏覽器
   final String userAgent = request.getHeader("USER-AGENT").toLowerCase();
   if(userAgent.contains("firefox")){ //火狐瀏覽器
    fileName = new String(fileName.getBytes(), "ISO8859-1");
   }else{
    fileName = URLEncoder.encode(fileName, "UTF-8"); //其他瀏覽器
          fileName = fileName.Replace("+", "%20"); //encode后替換,解決空格問(wèn)題(其中%20是空格在UTF-8下的編碼 ,如果不這么寫,瀏覽器會(huì)用+代替空格)
   }
   response.setHeader("Content-Disposition", "attachment;filename=" +fileName + ".xls");//指定輸出文件名
   response.setContentType("application/msexcel");//定義輸出類型
   int rouNum = ensurePriceListToExcel(outputStream,paimaiMoneyVOList);
   LogEnum.LAW_WARE.info("【RiseAuctionAction.downLoadEnsurePriceExcel】導(dǎo)出成功,一共更新了{(lán)"+rouNum+"}條記錄");
  } catch (Exception e) {
   LogEnum.LAW_WARE.error("【RiseAuctionAction.downLoadEnsurePriceExcel】導(dǎo)出失敗,error is {}", e);
  }
 }

三、拓展(詳細(xì)的工具類開(kāi)發(fā))

如果你覺(jué)得上面寫的太簡(jiǎn)單了,可以繼續(xù)往下看,我把它整理出了“萬(wàn)能”的工具類,供大家參考。

package com.jd.pop.auction.util.excel;
import com.jd.common.web.result.Result;
import com.jd.pop.auction.util.excel.annotations.ExcelColumn;
import com.jd.pop.auction.util.excel.annotations.ExcelMapping;
import com.jd.pop.auction.util.excel.annotations.apt.ExcelColumnAPT;
import com.jd.pop.auction.util.excel.annotations.apt.ExcelMappingAPT;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
public class GenerateExcel {
 private final static Logger LOG = Logger.getLogger(GenerateExcel.class);
 private HSSFWorkbook workbook;
 private HSSFCellStyle headStyle;
 private HSSFFont headCellFont;
 private HSSFCellStyle theadStyle;
 private HSSFFont theadCellFont;
 private HSSFCellStyle tbodyStyle;
 private HSSFFont tbodyCellFont;
 private HSSFFont stringFont;
 private static final short COLUMN_WIDTH = 15;
 private static final short ROW_HEIGHT = 400;
 public GenerateExcel() {
  this.workbook = new HSSFWorkbook();
  //標(biāo)題
  this.headStyle = workbook.createCellStyle();
  headStyle.setFillForegroundColor(HSSFColor.GREY_50_PERCENT.index);
  headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
//  headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//  headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//  headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
//  headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

//  headStyle.setWrapText(true);
  this.headCellFont = workbook.createFont();
  headCellFont.setFontHeightInPoints((short)13);
  headCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  headStyle.setFont(headCellFont);
  this.theadStyle = workbook.createCellStyle();
  theadStyle.setFillForegroundColor(HSSFColor.WHITE.index);
  theadStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  theadStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  theadStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  theadStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  theadStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  theadStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  theadCellFont = workbook.createFont();
  theadCellFont.setColor(HSSFColor.BLACK.index);
  theadCellFont.setFontHeightInPoints((short) 12);
  theadCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
  theadStyle.setFont(theadCellFont);
  tbodyStyle = workbook.createCellStyle();
  tbodyStyle.setFillForegroundColor(HSSFColor.WHITE.index);
  tbodyStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
  tbodyStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
  tbodyStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
  tbodyStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
  tbodyStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
  tbodyStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
  tbodyStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
  tbodyCellFont = workbook.createFont();
  tbodyCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
  tbodyStyle.setFont(tbodyCellFont);
  stringFont = workbook.createFont();
  stringFont.setColor(HSSFColor.BLACK.index);
 }
 public <T> Result export(List<String> titles, Field[] fields, Class clazz, Collection<T> dataset, OutputStream out, boolean pager) {
  Result result = new Result(false);
  if(pager){
  }else{
   HSSFSheet sheet = workbook.createSheet( "第一頁(yè)");
   sheet.setDefaultColumnWidth(COLUMN_WIDTH);
   sheet.setDefaultRowHeight(ROW_HEIGHT);
   //標(biāo)題
   for (int i = 0; i <titles.size(); i++) {
    HSSFRow titleRow = sheet.createRow(i);
    titleRow.setHeightInPoints(20f);
    sheet.addMergedRegion(new CellRangeAddress(i,i,0,fields.length-1));
    HSSFCell titleCell =titleRow.createCell(0);
    titleCell.setCellValue(titles.get(i));
    titleCell.setCellStyle(headStyle);
   }
   //列名
   HSSFRow row = sheet.createRow(titles.size());
   for (short i = 0; i < fields.length; i++) {
    HSSFCell cell = row.createCell(i);
    cell.setCellStyle(theadStyle);
    if(fields[i].isAnnotationPresent(ExcelColumn.class)){
     ExcelColumn an_1 = fields[i].getAnnotation(ExcelColumn.class);
     HSSFRichTextString text = new HSSFRichTextString(an_1.name());
     cell.setCellValue(text);
    }else if(fields[i].isAnnotationPresent(ExcelMapping.class)){
     ExcelMapping an_1 = fields[i].getAnnotation(ExcelMapping.class);
     HSSFRichTextString text = new HSSFRichTextString(an_1.name());
     cell.setCellValue(text);
    }
   }
   Iterator<T> it = dataset.iterator();
   int index = titles.size();
   while (it.hasNext()) {
    index++;
    row = sheet.createRow(index);
    T t = (T) it.next();
    for (short i = 0; i < fields.length; i++) {
     HSSFCell cell = row.createCell(i);
     cell.setCellStyle(tbodyStyle);
     Field field = fields[i];
     try {
      String textValue;
      if(field.isAnnotationPresent(ExcelMapping.class)){
       textValue = new ExcelMappingAPT().getColumnValue(field,t,clazz);
      }else{
       textValue = new ExcelColumnAPT().getColumnValue(field,t,clazz);
      }
      cell.setCellValue(textValue);
     } catch (NoSuchMethodException e) {
      String errorMsg = field.getName() +"字段,第"+ index+ "條數(shù)據(jù), NoSuchMethodException 反射錯(cuò)誤!";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     } catch (IllegalAccessException e) {
      String errorMsg = field.getName() +"字段,第"+ index+ "條數(shù)據(jù), IllegalAccessException ";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     } catch (InvocationTargetException e) {
      String errorMsg = field.getName() +"字段,第"+ index+ "條數(shù)據(jù), InvocationTargetException ";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     }
    }
   }
  }
  try {
   workbook.write(out);
   result.setSuccess(true);
   return result;
  } catch (IOException e) {
   String errorMsg = "將導(dǎo)出數(shù)據(jù)寫入輸出流失敗!";
   LOG.error("將導(dǎo)出數(shù)據(jù)寫入輸出流失??! ",e);
   result.addDefaultModel(errorMsg);
   return result;
  }finally {
   try {
    out.close();
   } catch (IOException e) {
    String errorMsg = "關(guān)閉輸出流異常!";
    LOG.error("關(guān)閉輸出流異常! ",e);
    result.addDefaultModel(errorMsg);
    return result;
   }
  }
 }
}
public class ExportExcelUtils {
 private final static Logger LOG = Logger.getLogger(ExportExcelUtils.class);
 public static <T> Result export(List<String> titles,List<T> sourceList, OutputStream out, boolean pager){
  Result result = new Result(false);
  if(CollectionUtils.isEmpty(sourceList)){
   result.addDefaultModel("ExportExcelUtils's param sourceList is empty!");
   LOG.error("ExportExcelUtils's param sourceList is empty!");
   return result;
  }
  if( out == null){
   LOG.error("ExportExcelUtils's param OutputStream is null!");
   result.addDefaultModel("ExportExcelUtils's param OutputStream is null!");
   return result;
  }
  Class clazz = null;
  Field[] fieldArr = null;
  try{
   //得到需要轉(zhuǎn)換的列名
   clazz = sourceList.get(0).getClass();
   Field[] fields = clazz.getDeclaredFields();
   List<Field> fieldList = new ArrayList<Field>();
   for(Field field:Arrays.asList(fields)){
    field.setAccessible(true);
    if(field.isAnnotationPresent(ExcelColumn.class)){
     fieldList.add(field);
    }else if(field.isAnnotationPresent(ExcelMapping.class)){
     fieldList.add(field);
    }
   }
   if(CollectionUtils.isEmpty(fieldList)){
    LOG.error("實(shí)體類中無(wú)需要導(dǎo)出的字段!");
    result.addDefaultModel("實(shí)體類中無(wú)需要導(dǎo)出的字段!");
    return result;
   }
   fieldArr = fieldList.toArray(new Field[fieldList.size()]);
  }catch(Exception e){
   LOG.error("數(shù)據(jù)拼裝異常!");
   result.addDefaultModel("數(shù)據(jù)拼裝異常!");
   return result;
  }
  //生成excel
  GenerateExcel ge = new GenerateExcel();
  return ge.export(titles,fieldArr,clazz,sourceList,out,false);
 }

}

這一部分寫的比較粗糙,但是實(shí)現(xiàn)的比較詳細(xì),僅供參考,大家可以稍微改造成為自己獨(dú)有的utils。

以上就是本文的全部?jī)?nèi)容,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,同時(shí)也希望多多支持腳本之家!

相關(guān)文章

  • JAVA使用Ip2region獲取IP定位信息的操作方法

    JAVA使用Ip2region獲取IP定位信息的操作方法

    這篇文章主要介紹了JAVA使用Ip2region獲取IP定位信息,ip2region?-?是國(guó)內(nèi)開(kāi)發(fā)者開(kāi)發(fā)的離線IP地址定位庫(kù),針對(duì)國(guó)內(nèi)IP效果較好,國(guó)外的部分IP只能顯示國(guó)家,對(duì)java獲取IP定位信息操作過(guò)程感興趣的朋友一起看看吧
    2022-05-05
  • Java main 方法面試題的詳細(xì)整理

    Java main 方法面試題的詳細(xì)整理

    這篇文章主要介紹了Java main 方法面試題的詳細(xì)整理的相關(guān)資料,這里介紹了10個(gè)經(jīng)典面試題的方法,需要的朋友可以參考下
    2017-09-09
  • Struts2通過(guò)自定義標(biāo)簽實(shí)現(xiàn)權(quán)限控制的方法

    Struts2通過(guò)自定義標(biāo)簽實(shí)現(xiàn)權(quán)限控制的方法

    這篇文章主要介紹了Struts2通過(guò)自定義標(biāo)簽實(shí)現(xiàn)權(quán)限控制的方法,介紹了定義Struts2的自定義標(biāo)簽的三個(gè)步驟以及詳細(xì)解釋,需要的朋友可以參考下。
    2017-09-09
  • springBoot 與neo4j的簡(jiǎn)單整合示例

    springBoot 與neo4j的簡(jiǎn)單整合示例

    這篇文章主要介紹了springBoot 與neo4j的簡(jiǎn)單整合示例,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-01-01
  • Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能示例

    Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能示例

    這篇文章主要介紹了Java實(shí)現(xiàn)的時(shí)間戳與date對(duì)象相互轉(zhuǎn)換功能,結(jié)合具體實(shí)例形式分析了java日期與時(shí)間戳類型的表示與轉(zhuǎn)換相關(guān)操作技巧,需要的朋友可以參考下
    2017-06-06
  • Java實(shí)現(xiàn)雪花算法的原理和實(shí)戰(zhàn)教程

    Java實(shí)現(xiàn)雪花算法的原理和實(shí)戰(zhàn)教程

    這篇文章主要介紹了Java實(shí)現(xiàn)雪花算法的原理和實(shí)戰(zhàn)教程,本文通過(guò)語(yǔ)言表述和代碼的實(shí)現(xiàn)講解了該項(xiàng)算法,,需要的朋友可以參考下
    2021-06-06
  • Spring Web項(xiàng)目spring配置文件隨服務(wù)器啟動(dòng)時(shí)自動(dòng)加載

    Spring Web項(xiàng)目spring配置文件隨服務(wù)器啟動(dòng)時(shí)自動(dòng)加載

    這篇文章主要介紹了Spring Web項(xiàng)目spring配置文件隨服務(wù)器啟動(dòng)時(shí)自動(dòng)加載,加載spring的配置文件,并且只加載一次,從而提高程序效率。具體內(nèi)容詳情大家通過(guò)本文一起學(xué)習(xí)吧
    2018-01-01
  • 淺談Java中BigDecimal類的簡(jiǎn)單應(yīng)用

    淺談Java中BigDecimal類的簡(jiǎn)單應(yīng)用

    這篇文章主要介紹了淺談Java中BigDecimal類的簡(jiǎn)單應(yīng)用,BigDecimal是由任意精度的整數(shù)非標(biāo)度值和32位的整數(shù)標(biāo)度組成,如果為零或正數(shù),則標(biāo)度是小數(shù)點(diǎn)后的位數(shù),如果為負(fù)數(shù),則將該數(shù)的非標(biāo)度值乘以?10的負(fù)scale次冪,需要的朋友可以參考下
    2023-07-07
  • Spring實(shí)現(xiàn)內(nèi)置監(jiān)聽(tīng)器

    Spring實(shí)現(xiàn)內(nèi)置監(jiān)聽(tīng)器

    這篇文章主要介紹了Spring 實(shí)現(xiàn)自定義監(jiān)聽(tīng)器案例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧,希望能給你帶來(lái)幫助
    2021-07-07
  • SpringBoot中封裝Cors自動(dòng)配置方式

    SpringBoot中封裝Cors自動(dòng)配置方式

    這篇文章主要介紹了SpringBoot中封裝Cors自動(dòng)配置方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2025-03-03

最新評(píng)論

商南县| 武胜县| 从化市| 海原县| 黑水县| 南康市| 武夷山市| 安龙县| 沙田区| 得荣县| 庆城县| 库尔勒市| 遂昌县| 双流县| 易门县| 庄浪县| 综艺| 乐平市| 马关县| 凤凰县| 科尔| 镇坪县| 田阳县| 讷河市| 阿合奇县| 察雅县| 林西县| 成都市| 自贡市| 宣化县| 清水河县| 永顺县| 商水县| 彰化市| 蛟河市| 抚州市| 布尔津县| 莲花县| 临清市| 来凤县| 安龙县|