Java通过apache poi生成excel实例代码

本篇文章主要介绍了Java通过apache poi生成excel实例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

首先,jar

maven 添加依赖

org.apache.poipoi-ooxml3.15

开始以为是poi,然后就直接加poi的依赖,谁知道并没有所需要的类。查了查才发现是poi-ooxml

要用到的类

XSSFWorkbook , 代表一个excel文档

XSSFSheet , 代表文档中的一个sheet

XSSFRow , 代表sheet中的一行

XSSFCell , 代表row中的每一项的值

最最基本的使用

//创建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();

小例子一枚

利用反射,把bean类中各属性(用getXxx取出),写入到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 void getExcel(List list,Class c,OutputStream output) throws IOException, illegalaccessexception, IllegalArgumentException, InvocationTargetException{ Map methodMap = new LinkedHashMap(); Method[] methods = c.getDeclaredMethods(); for(int i=0;i

App.java 进行测试使用

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 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(); } }

测试结果截图

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

相关文章

Java中的String是不可变对象 在面向对象及函数编程语言中,不...
String, StringBuffer 和 StringBuilder 可变性 String不可变...
序列化:把对象转换为字节序列的过程称为对象的序列化. 反序...
先说结论,是对象!可以继续往下看 数组是不是对象 什么是对...
为什么浮点数 float 或 double 运算的时候会有精度丢失的风险...
面试题引入 这里引申出一个经典问题,看下面代码 Integer a ...