首页 > 网站 > Apache > 正文

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

2024-08-27 18:25:22
字体:
来源:转载
供稿:网友

首先,jar

maven 添加依赖

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

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

要用到的类

XSSFWorkbook , 代表一个excel文档 XSSFSheet , 代表文档中的一个sheet XSSFRow , 代表sheet中的一行 XSSFCell , 代表row中的每一项的值

最最基本的使用

//创建excel文档XSSFWorkbook workbook = new XSSFWorkbook();//创建sheetXSSFSheet sheet = workbook.createSheet("sheetName");int rownum=0;//创建首行XSSFRow firstrow = sheet.createRow(rownum++);int cellnum = 0;//把保存在titles中的各个列名,分别在row中创建cellfor(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 <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(); } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表