Home  >  Article  >  Java  >  Detailed example of how Java generates excel through apache poi

Detailed example of how Java generates excel through apache poi

黄舟
黄舟Original
2017-06-04 09:13:562074browse

This article mainly introduces Java to generate excel example code through apache poi. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor to take a look.

First, jar

maven adds dependencies

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.15</version>
</dependency>

At first I thought it was poi, and then I went directly Add the dependency of poi, who knows that there is no required class. After checking, I found out that it is the class to be used by poi-ooxml

  1. XSSFWorkbook, which represents an excel document

  2. XSSFSheet, represents a sheet in the document

  3. XSSFRow, represents a row in the sheet

  4. XSSFCell, represents the row The value of each item

The most basic use

//创建excel文档
XSSFWorkbook workbook = new XSSFWorkbook();
//创建sheet
XSSFSheet sheet = workbook.createSheet("sheetName");

int rownum=0;
//创建首行
XSSFRow firstrow = sheet.createRow(rownum++);
int cellnum = 0;
//把保存在titles中的各个列名,分别在row中创建cell
for(String key : titles){
 XSSFCell cell = firstrow.createCell(cellnum++);
 cell.setCellValue(key);
}


//下面可以继续创建行

//把excel写到要写的outputStream中
workbook.write(output);
//最后关闭
workbook.close();

A small example

Use reflection to write each attribute (retrieved with getXxx) in the bean class into excel

ExcelUtil.java

package me.paul.excelDemo;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class ExcelUtil {
 
 public <T> void getExcel(List<T> list,Class<T> c,OutputStream output) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
 Map<String,Method> methodMap = new LinkedHashMap<>(); 
 Method[] methods = c.getDeclaredMethods();
 for(int i=0;i<methods.length;i++){
  Method method = methods[i];
  String name = method.getName();
  Pattern pattern = Pattern.compile("get(.*)");
  Matcher matcher = null;
  if((matcher = pattern.matcher(name)).matches()){
  name = matcher.group(1);
  char ch = name.charAt(0);
  char newch = (char) (ch + 32); 
  name = name.replace(ch,newch);
  methodMap.put(name, method);
  }
 }
 
 XSSFWorkbook workbook = new XSSFWorkbook();
 XSSFSheet sheet = workbook.createSheet(c.getCanonicalName());
 int rownum=0;
 XSSFRow firstrow = sheet.createRow(rownum++);
 int cellnum = 0;
 for(String key : methodMap.keySet()){
  XSSFCell cell = firstrow.createCell(cellnum++);
  cell.setCellValue(key);
 }
 
 for(T t : list){
  XSSFRow row = sheet.createRow(rownum++);
  cellnum = 0;
  for(String key:methodMap.keySet()){
  Method method = methodMap.get(key);
                //设置可访问,之前不知道这方法,所以关于反射那篇文章有错误,见谅见谅
                method.setAccessible(true);
  Object obj = method.invoke(t);
  XSSFCell cell = row.createCell(cellnum++);
  cell.setCellValue(obj== null ? "":obj.toString());
  }
  
 }
 workbook.write(output);
 workbook.close();
 } 
}

App.java Test using

package me.paul.excelDemo;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class App {
 public static void main(String[] args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException {
 List<User> list = new ArrayList<>();
 User u = new User();
 u.setId(1);
 u.setName("Paul");
 u.setAge(18);
 list.add(u);
 u = new User();
 u.setId(2);
 u.setName("Johnson");
 u.setAge(20);
 list.add(u);
 u = new User();
 u.setId(3);
 u.setName("David");
 u.setAge(22);
 list.add(u);
 OutputStream output = new FileOutputStream("/home/paul/user.xlsx");
 new ExcelUtil().getExcel(list, User.class,output);
 output.close();
 }
}

Screenshot of test results

The above is the detailed content of Detailed example of how Java generates excel through apache poi. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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