Apache POI操作Excel导出JAVABEAN对象方法
2019独角兽企业重金招聘Python工程师标准>>>
Apache POI操作Excel导出方法说明
Apache的POI组件是Java操作Microsoft Office办公套件的强大API,其中对Word,Excel和PowperPoint都有支持,当然使用较多的还是Excel,因为Word和PowerPoint用程序动态操作的应用较少。本文主要介绍一下Excel的操作方法。
- HSSF - 提供读写 Microsoft ExcelXLS格式档案的功能。
- XSSF - 提供读写 Microsoft ExcelOOXML XLSX格式档案的功能。
- HWPF - 提供读写 Microsoft WordDOC格式档案的功能。
- HSLF - 提供读写 MicrosoftPowerPoint格式档案的功能。
- HDGF - 提供读 Microsoft Visio格式档案的功能。
- HPBF - 提供读 MicrosoftPublisher格式档案的功能。
- HSMF - 提供读 Microsoft Outlook格式档案的功能。
EXCEL单元格样式设置:
// 创建字体 HSSFFont font = wb.createFont(); // 设置字体为红色 font.setColor(HSSFFont.COLOR_RED); // 设置字体为粗体 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 创建单元格格式 HSSFCellStyle cellStyle= wb.createCellStyle(); // 设置字体 cellStyle.setFont(font); // 设置水平居中 cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 设置垂直靠下 cellStyle.setVerticalAlignment(CellStyle.VERTICAL_BOTTOM); // 设置左边框为双线 cellStyle.setBorderLeft(CellStyle.BORDER_DOUBLE); // 设置背景色为蓝色 cellStyle.setFillBackgroundColor(new HSSFColor.BLUE().getIndex()); // 设置前景色为黄色 cellStyle.setFillForegroundColor(new HSSFColor.YELLOW().getIndex());
Excel导出:
第一种,利用JAVA反射导出:
POIExcelUtil 类:
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class POIExcelUtil {public static final String FILE_EXTENSION_XLS = "xls";public static final String FILE_EXTENSION_XLSX = "xlsx";/*** * @param Map* <String,String> maps 属性表,成员属性age为KEY,中文名称为VALUE* @param List* <T> list 需要导出的数据列表对象* @param File* file 指定输出文件位置,只能导出excel2003以上版本* * @return true 导出成功 false 导出失败*/public static <T> boolean excelExport(Map<String, String> maps, List<T> list, File file) {try {Workbook wb = null;String filename = file.getName();String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if (type.equals(FILE_EXTENSION_XLS)) {wb = new HSSFWorkbook();}if (type.equals(FILE_EXTENSION_XLSX)) {wb = new XSSFWorkbook();}CreationHelper createHelper = wb.getCreationHelper();Sheet sheet = wb.createSheet("sheet1");Set<String> sets = maps.keySet();Row row = sheet.createRow(0);int i = 0;// 定义表头for (Iterator<String> it = sets.iterator(); it.hasNext();) {String key = it.next();Cell cell = row.createCell(i++);cell.setCellValue(createHelper.createRichTextString(maps.get(key)));}// 填充表单内容System.out.println("--------------------100%");float avg = list.size() / 20f;int count = 1;for (int j = 0; j < list.size(); j++) {T p = list.get(j);Class classType = p.getClass();int index = 0;Row row1 = sheet.createRow(j+1);for (Iterator<String> it = sets.iterator(); it.hasNext();) {String key = it.next();String firstLetter = key.substring(0, 1).toUpperCase();// 获得和属性对应的getXXX()方法的名字String getMethodName = "get" + firstLetter+ key.substring(1);// 获得和属性对应的getXXX()方法Method getMethod = classType.getMethod(getMethodName,new Class[] {});// 调用原对象的getXXX()方法Object value = getMethod.invoke(p, new Object[] {});Cell cell = row1.createCell(index++);cell.setCellValue(value.toString());}if (j > avg * count) {count++;System.out.print("I");}if (count == 20) {System.out.print("I100%");count++;}}FileOutputStream fileOut = new FileOutputStream(file);wb.write(fileOut);fileOut.close();} catch (IOException e) {e.printStackTrace();return false;} catch (SecurityException e) {e.printStackTrace();return false;} catch (NoSuchMethodException e) {e.printStackTrace();return false;} catch (IllegalArgumentException e) {e.printStackTrace();return false;} catch (IllegalAccessException e) {e.printStackTrace();return false;} catch (InvocationTargetException e) {e.printStackTrace();return false;}return true;}
}
第二种:利用JAVA反射和Annotation导出
POIExcelAnnotation 类:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface POIExcelAnnotation {public String titleName();
}
POIExcelUtil 类:
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class POIExcelUtil {public static final String FILE_EXTENSION_XLS = "xls";public static final String FILE_EXTENSION_XLSX = "xlsx";/*** * @param sheetName sheet名称* @param pojoClass POJO对象类* @param list 导出数据列表* @param file file 指定输出文件* @return true 导出成功 false 导出失败*/public static <T> boolean excelAnnotationExport(String sheetName ,Class<T> pojoClass,List<T> list, File file) {try {Workbook wb = null;String filename = file.getName();String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if (type.equals(FILE_EXTENSION_XLS)) {wb = new HSSFWorkbook();}if (type.equals(FILE_EXTENSION_XLSX)) {wb = new XSSFWorkbook();}CreationHelper createHelper = wb.getCreationHelper();Sheet sheet = wb.createSheet(sheetName);// 标题 List<String> fieldTitle = new ArrayList<String>(); //方法列表,对应表头List<Method> methodObj = new ArrayList<Method>(); // 得到所有字段 Field fileds[] = pojoClass.getDeclaredFields(); // 遍历整个filed for (int i = 0; i < fileds.length; i++) { Field field = fileds[i]; POIExcelAnnotation annotation = field.getAnnotation(POIExcelAnnotation.class); // 如果设置了annottion if (annotation != null) { // 添加到标题 fieldTitle.add(annotation.titleName()); // 添加到需要导出的字段的方法 String fieldName = field.getName(); String firstLetter = fieldName.substring(0, 1).toUpperCase();// 获得和属性对应的getXXX()方法的名String getMethodName = "get" + firstLetter+ fieldName.substring(1);// 获得和属性对应的getXXX()方法Method getMethod = pojoClass.getMethod(getMethodName,new Class[] {}); methodObj.add(getMethod); } }//设置表头粗体Font font = wb.createFont();font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);CellStyle style = wb.createCellStyle();style.setFont(font);//填充表头内容Row row = sheet.createRow(0);for(int i=0;i<fieldTitle.size();i++){String title = fieldTitle.get(i);Cell cell = row.createCell(i);cell.setCellStyle(style);cell.setCellValue(createHelper.createRichTextString(title));}// 填充表单内容System.out.println("--------------------100%");float avg = list.size() / 20f;int count = 1;for (int j = 0; j < list.size(); j++) {T p = list.get(j);Row row1 = sheet.createRow(j+1); for (int k=0;k<methodObj.size();k++) {Method getMethod = methodObj.get(k);Object value = getMethod.invoke(p, new Object[] {});Cell cell = row1.createCell(k);cell.setCellValue(value.toString());}if (j > avg * count) {count++;System.out.print("I");}if (count == 20) {System.out.println("I100%");count++;}}FileOutputStream fileOut = new FileOutputStream(file);wb.write(fileOut);fileOut.close();} catch (IOException e) {e.printStackTrace();return false;} catch (SecurityException e) {e.printStackTrace();return false;} catch (NoSuchMethodException e) {e.printStackTrace();return false;} catch (IllegalArgumentException e) {e.printStackTrace();return false;} catch (IllegalAccessException e) {e.printStackTrace();return false;} catch (InvocationTargetException e) {e.printStackTrace();return false;}return true;}
}
调用方法截取代码:
public static void main(String args[]){ List<JavaBean> demo = ****;Map<String,String> maps = new LinkedHashMap<String,String>();maps.put("uid", "帐号");maps.put("cn", "姓名");maps.put("dept", "部门");maps.put("mail", "邮箱");Properties props = System.getProperties();String USER_HOME = props.getProperty("user.home");File file = new File(USER_HOME + "/Desktop/excelExport.xlsx");POIExcelUtil.excelExport(maps, demo , file);
}
Excel导入:
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class POIExcelUtil {public static final String FILE_EXTENSION_XLS = "xls";public static final String FILE_EXTENSION_XLSX = "xlsx";@SuppressWarnings("unchecked")public static List importExcel(File file ){List list = new ArrayList();Workbook wb = null;String filename = file.getName();String type = filename.substring(filename.lastIndexOf(".")+1).toLowerCase();if (type.equals(FILE_EXTENSION_XLS)) {wb = new HSSFWorkbook();}if (type.equals(FILE_EXTENSION_XLSX)) {wb = new XSSFWorkbook();}Sheet sheet = wb.getSheetAt(0);for(int i=1;i<sheet.getLastRowNum();i++){Row row = sheet.getRow(i);//以下代码,根据需求自由变化for(int j=0;j<row.getLastCellNum();j++){Cell cell = row.getCell(j); list.add(cell.getRichStringCellValue().getString());}}return list;}
}
转载于:https://my.oschina.net/u/154628/blog/262290
Apache POI操作Excel导出JAVABEAN对象方法相关推荐
- Apache POI操作Excel的坑
本文记录一下用Apache POI操作Excel时可能遇到一些坑. excel版本错误 首先是excel版本问题,由于office excel 03版和07版的区别,在读取文件时如果版本不匹配会报以下 ...
- Apache POI操作Excel文件
Apache POI是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用PO ...
- (6) 如何用Apache POI操作Excel文件-----POI-3.10的一个和注解(comment)相关的另外一个bug...
如果POI-3.10往一个工作表(sheet)里面插入数据的话,需要注意了,其有一个不太被容易发现的bug. 被插入的工作表(sheet)里面的单元格没有包含任何的注解(comment)的时候,插入一 ...
- 如何用Apache POI操作Excel文件-----如何对一个单元格加注解?
有的时候,我们需要通过操作Apache POI,在生成Cell数据的同时,能对其生成的Cell,加上注解(comments),类似于下面的. 那么对于这种情况,我们的代码应该如何写呢? 借花献佛,我就 ...
- 如何用Apache POI操作Excel文件-----如何在已有的Excel文件中插入一行新的数据?
在POI的第一节入门中,我们提供了两个简单的例子,一个是如何用Apache POI新建一个工作薄,另外一个例子是,如果用Apache POI新建一个工作表.那么在这个章节里面,我将会给大家演示一下,如 ...
- 如何用Apache POI操作Excel文件-----如何用Apache POI 画一个离散图
有的时候,我们需要Excel中的数据,通过一个图画,可视化的表现出来. 那么这个时候,应该如何做呢?现在就借花献佛,以Apache POI自己提供的一个例子为例,给大家演示一下POI的API 如何画图 ...
- Apache POI 操作Excel常用方法
文章目录 一.Apache POI 介绍 二.Apache POI中的常用方法 1.新建工作簿和工作表 1.新建工作簿 2.新建工作表 3.打开一个excel 4.将excel输出 2.创建单元格 1 ...
- java使用poi操作excel文件_使用 java apache poi 操作 excel xlsx 文件
工作中临时需要对各种订单量进行简单的统计分析,为了方便简单学习了apache poi 对 xlsx 文件的基本操作,简单记录 1. 引包 org.apache.poi poi-ooxml 4.1.2 ...
- 采用APACHE POI操作EXCEL文件--计算式调用另一文件
http://blog.sina.com.cn/s/blog_6151984a0100sczi.html 测试环境: 当前EXCEL文件: workbook.xls 假设一个CELL的计算式如下: ...
最新文章
- es创建索引设置字段不分词_ES的使用笔记
- delphi创建和读取xml(xml简单操作举例)
- sizeof _countof _tcslen的比较
- 三态门有一个信号控制端en_W25Q32JVSSIQ|哪些PCB设计会影响信号质量?
- java 设计模式_快速上手Java设计模式之简介
- Hazelcast入门指南第4部分
- python实现程序重启_python实现自动重启本程序的方法
- CVPR2020 | 华为GhostNet超越谷歌MobileNetV3
- 服务器维保价格标准_汽车后市场大数据研究报告:《汽车后市场乘用车维保行业白皮书》...
- 一个真正成熟的人不会过度在意别人的眼光
- 数据结构复习之【线性表】
- mac 版 SourceTree(git 客户端)跳过登录验证
- 红米5a android,红米5A值得买吗?红米5A测评告诉你(附全文)
- c语言中不带任何修饰符的浮点常量是按,C语言练习题参考答案
- asc和desc全称_MySQL数据排序asc、desc
- java导出excel 自定义表头
- 互联网创新创业大赛优秀范例_创新创业大赛优秀作品-互联网+大赛作品
- Lesson 5英语句子成分
- Python软件编程等级考试三级——20220319
- 基础算法-高精度乘法