Home Java javaTutorial Sharing sample code for java to implement the function of exporting object arrays through excel

Sharing sample code for java to implement the function of exporting object arrays through excel

Mar 29, 2017 am 11:05 AM

This article mainly introduces the relevant knowledge of java to implement the function of exporting objectsarray through excel. It has a very good reference value. Let’s take a look at it with the editor.

1. Import the relevant jar package. The pom dependencies are as follows:

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

2 , Start coding

1. If the export function is used a lot, you can make it into a tool class and modify the code I posted below

//结果返回的是写入的记录数(以下用的是自己业务场景数据)
  public int downLoadToExcel(OutputStream outputStream,List<PaimaiMoneyVO> paimaiMoneyVOList) {
     //文档对象
  HSSFWorkbook wb = new HSSFWorkbook();
  int rowNum = 0;
  Sheet sheet = wb.createSheet("excel的标题");
  Row row0 = sheet.createRow(rowNum++);
    //因为场景不同,titil不同,可以在外面写成数组当参数传进来
  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("升价拍"); 
    row.createCell(5).setCellValue(bidder);
   }
  }
  try {
   wb.write(outputStream);
   LogEnum.LAW_WARE.info("表数据写入到excel表成功,一共写入了"+(rowNum - 1)+"条数据");
   outputStream.close();
  } catch (IOException e) {
   LogEnum.LAW_WARE.error("流关闭异常!", e);
  } finally {
   if (outputStream != null) {
    try {
     outputStream.close();
    } catch (IOException e) {
     LogEnum.LAW_WARE.error("流关闭异常!", e);
    }
   }
  }
  return rowNum - 1;
 }
Copy after login

#2. After the "Tool Class" is written, we will start using it. From the function parameters above, we can see that we need Pass two objects, one is the output stream OutPutStream, and the excel is sent to the browser through the stream.

The other is the array of objects we need to export. Okay, no Too many explanations, look at the code. (The following method is written in the action layer, and can be downloaded through struts.xml configuration access)

public void exportBail(){
  this.fileName = "excel文件名";
  try {
   List<PaimaiMoneyVO> paimaiMoneyVOList = new ArrayList<>();
      //下面是我的业务场景获取对象数组
   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();//清空输出流
   //下面是对中文文件名的处理
   response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
       //解析浏览器
   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后替换,解决空格问题(其中%20是空格在UTF-8下的编码 ,如果不这么写,浏览器会用+代替空格)
   }
   response.setHeader("Content-Disposition", "attachment;filename=" +fileName + ".xls");//指定输出文件名
   response.setContentType("application/msexcel");//定义输出类型
   int rouNum = ensurePriceListToExcel(outputStream,paimaiMoneyVOList);
   LogEnum.LAW_WARE.info("【RiseAuctionAction.downLoadEnsurePriceExcel】导出成功,一共更新了{"+rouNum+"}条记录");
  } catch (Exception e) {
   LogEnum.LAW_WARE.error("【RiseAuctionAction.downLoadEnsurePriceExcel】导出失败,error is {}", e);
  }
 }
Copy after login

3. Expansion (detailed tool development)

If you feel that what is written above is too simple, you can continue reading below. I have sorted it out into "universal" tool categories for your reference.

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();
  //标题
  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( "第一页");
   sheet.setDefaultColumnWidth(COLUMN_WIDTH);
   sheet.setDefaultRowHeight(ROW_HEIGHT);
   //标题
   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+ "条数据, NoSuchMethodException 反射错误!";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     } catch (IllegalAccessException e) {
      String errorMsg = field.getName() +"字段,第"+ index+ "条数据, IllegalAccessException ";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     } catch (InvocationTargetException e) {
      String errorMsg = field.getName() +"字段,第"+ index+ "条数据, InvocationTargetException ";
      LOG.error(errorMsg,e);
      result.addDefaultModel(errorMsg);
      return result;
     }
    }
   }
  }
  try {
   workbook.write(out);
   result.setSuccess(true);
   return result;
  } catch (IOException e) {
   String errorMsg = "将导出数据写入输出流失败!";
   LOG.error("将导出数据写入输出流失败! ",e);
   result.addDefaultModel(errorMsg);
   return result;
  }finally {
   try {
    out.close();
   } catch (IOException e) {
    String errorMsg = "关闭输出流异常!";
    LOG.error("关闭输出流异常! ",e);
    result.addDefaultModel(errorMsg);
    return result;
   }
  }
 }
}
Copy after login
rrree

The above is the detailed content of Sharing sample code for java to implement the function of exporting object arrays through excel. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Square Root in Java Square Root in Java Aug 30, 2024 pm 04:26 PM

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Random Number Generator in Java Random Number Generator in Java Aug 30, 2024 pm 04:27 PM

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Armstrong Number in Java Armstrong Number in Java Aug 30, 2024 pm 04:26 PM

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

See all articles