使用写入excel工具类的例子

说明:改工具类是网上公开的,来源现在找不着了,我只是在原基础上修改了下,抽离了泛型。如有侵权,请通知博主

工具类代码:

package com.system.util;import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;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.HorizontalAlignment;
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.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;/*** * Author: laijieguan*/
public abstract class ExcelWriter<T> {public List<String> CELL_HEADS = new ArrayList<String>(); // 列头//  static {//      // 类装载时就载入指定好的列头信息,如有需要,可以考虑做成动态生成的列头
//      CELL_HEADS = new ArrayList<>();
//      CELL_HEADS.add("姓名");
//      CELL_HEADS.add("年龄");
//      CELL_HEADS.add("居住城市");
//      CELL_HEADS.add("职业");
//  }/*** 生成Excel并写入数据信息,无模板的读取方式* * @param dataList 数据列表* @return 写入数据后的工作簿对象* @throws IOException */public Workbook exportData(List<T> dataList,String type) {Workbook workbook =null;if("xlsx".equals(type)) {// 生成xlsx的Excelworkbook = new XSSFWorkbook();}else if("xls".equals(type)) {// 如需生成xls的Excel,请使用下面的工作簿对象,注意后续输出时文件后缀名也需更改为xlsworkbook = new HSSFWorkbook();}Sheet sheet = null;//判断是否需要生成第一行的数据头信息if(CELL_HEADS!=null && CELL_HEADS.size() >0) {// 生成Sheet表,写入第一行的列头sheet = buildDataSheet(workbook);}else {//不要生成sheet = workbook.getSheetAt(0);}// 构建每行的数据内容int rowNum = 1;for (Iterator<T> it = dataList.iterator(); it.hasNext();) {T data = it.next();if (data == null) {continue;}// 输出行数据Row row = sheet.createRow(rowNum++);convertDataToRow(data, row);}return workbook;}/*** 生成Excel并写入数据信息,有模板的读取方式* * @param dataList 数据列表* @return 写入数据后的工作簿对象* @throws IOException */public Workbook exportDataTem(List<T> dataList,String templateName) throws Exception {Workbook workbook =null;FileInputStream fis = new FileInputStream(templateName);if(templateName.endsWith("xlsx")) {// 生成xlsx的Excelworkbook = new XSSFWorkbook(fis);}else if(templateName.endsWith("xls")) {// 如需生成xls的Excel,请使用下面的工作簿对象,注意后续输出时文件后缀名也需更改为xlsworkbook = new HSSFWorkbook(fis);}Sheet sheet = null;//判断是否需要生成第一行的数据头信息if(CELL_HEADS!=null && CELL_HEADS.size() >0) {// 生成Sheet表,写入第一行的列头sheet = buildDataSheet(workbook);}else {//不要生成sheet = workbook.getSheetAt(0);}// 构建每行的数据内容int rowNum = 1;for (Iterator<T> it = dataList.iterator(); it.hasNext();) {T data = it.next();if (data == null) {continue;}// 输出行数据Row row = sheet.createRow(rowNum++);convertDataToRow(data, row);}return workbook;}/*** 生成sheet表,并写入第一行数据(列头)* * @param workbook 工作簿对象* @return 已经写入列头的Sheet*/public Sheet buildDataSheet(Workbook workbook) {Sheet sheet = workbook.createSheet();// 设置列头宽度for (int i = 0; i < CELL_HEADS.size(); i++) {sheet.setColumnWidth(i, 4000);}// 设置默认行高sheet.setDefaultRowHeight((short) 400);// 构建头单元格样式//CellStyle cellStyle = buildHeadCellStyle(sheet.getWorkbook());// 写入第一行各列的数据Row head = sheet.createRow(0);for (int i = 0; i < CELL_HEADS.size(); i++) {Cell cell = head.createCell(i);cell.setCellValue(CELL_HEADS.get(i));//cell.setCellStyle(cellStyle);}return sheet;}/*** 设置第一行列头的样式* * @param workbook 工作簿对象* @return 单元格样式对象*//** private static CellStyle buildHeadCellStyle(Workbook workbook) { CellStyle* style = workbook.createCellStyle(); // 对齐方式设置* style.setAlignment(HorizontalAlignment.CENTER); // 边框颜色和宽度设置* style.setBorderBottom(BorderStyle.THIN);* style.setBottomBorderColor(IndexedColors.BLACK.getIndex()); // 下边框* style.setBorderLeft(BorderStyle.THIN);* style.setLeftBorderColor(IndexedColors.BLACK.getIndex()); // 左边框* style.setBorderRight(BorderStyle.THIN);* style.setRightBorderColor(IndexedColors.BLACK.getIndex()); // 右边框* style.setBorderTop(BorderStyle.THIN);* style.setTopBorderColor(IndexedColors.BLACK.getIndex()); // 上边框 // 设置背景颜色* style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());* style.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 粗体字设置 Font font =* workbook.createFont(); font.setBold(true); style.setFont(font); return style;* }*//*** 将数据转换成行 抽离泛型* * @param data 源数据* @param row  行对象* @return*/public abstract void convertDataToRow(T data, Row row);
}

现在有一个实体类是这样的


public class Country {/*** 国别代码*/private String countrycode;/*** 国别中文简称*/private String countryname;/*** 国别英文简称*/private String countryenname;/*** 国别英文缩写*/private String countryenshort;/*** 优普税率*/private String applytaxtype;/*** 国别描述*/private String countrydesc;/*** 备注*/private String comments;/*** 状态*/private String states;/*** 最终目的国别代码*/private String lastcountrycode;public String getCountrycode() {return countrycode;}public void setCountrycode(String countrycode) {this.countrycode = countrycode == null ? null : countrycode.trim();}public String getCountryname() {return countryname;}public void setCountryname(String countryname) {this.countryname = countryname == null ? null : countryname.trim();}public String getCountryenname() {return countryenname;}public void setCountryenname(String countryenname) {this.countryenname = countryenname == null ? null : countryenname.trim();}public String getCountryenshort() {return countryenshort;}/*** This method was generated by MyBatis Generator.* This method sets the value of the database column WL_COUNTRY.COUNTRYENSHORT** @param countryenshort the value for WL_COUNTRY.COUNTRYENSHORT** @mbg.generated Fri Jul 10 13:39:12 CST 2020*/public void setCountryenshort(String countryenshort) {this.countryenshort = countryenshort == null ? null : countryenshort.trim();}public String getApplytaxtype() {return applytaxtype;}public void setApplytaxtype(String applytaxtype) {this.applytaxtype = applytaxtype == null ? null : applytaxtype.trim();}public String getCountrydesc() {return countrydesc;}public void setCountrydesc(String countrydesc) {this.countrydesc = countrydesc == null ? null : countrydesc.trim();}public String getComments() {return comments;}public void setComments(String comments) {this.comments = comments == null ? null : comments.trim();}public String getStates() {return states;}public void setStates(String states) {this.states = states == null ? null : states.trim();}public String getLastcountrycode() {return lastcountrycode;}public void setLastcountrycode(String lastcountrycode) {this.lastcountrycode = lastcountrycode == null ? null : lastcountrycode.trim();}@Overridepublic String toString() {return "Country [countrycode=" + countrycode + ", countryname=" + countryname + ", countryenname="+ countryenname + ", countryenshort=" + countryenshort + ", applytaxtype=" + applytaxtype+ ", countrydesc=" + countrydesc + ", comments=" + comments + ", states=" + states+ ", lastcountrycode=" + lastcountrycode + "]";}}

继承工具类


import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;import com.system.util.ExcelWriter;
import com.wl.differentCountries.entity.Country;public class CountryExcelWriter extends ExcelWriter<Country> {@Overridepublic void convertDataToRow(Country data, Row row) {int cellNum = 0;Cell cell;// 国别代码cell = row.createCell(cellNum++);cell.setCellValue(null == data.getCountrycode() ? "" : data.getCountrycode());// 国别中文简称cell = row.createCell(cellNum++);cell.setCellValue(null == data.getCountryname() ? "" : data.getCountryname());// 国别英文简称cell = row.createCell(cellNum++);cell.setCellValue(null == data.getCountryenname() ? "" : data.getCountryenname());// 国别英文缩写cell = row.createCell(cellNum++);cell.setCellValue(null == data.getCountryenshort() ? "" : data.getCountryenshort());// 优普税率cell = row.createCell(cellNum++);cell.setCellValue(null == data.getApplytaxtype() ? "" : data.getApplytaxtype());// 国别描述cell = row.createCell(cellNum++);cell.setCellValue(null == data.getCountrydesc() ? "" : data.getCountrydesc());// 备注cell = row.createCell(cellNum++);cell.setCellValue(null == data.getComments() ? "" : data.getComments());// 状态cell = row.createCell(cellNum++);cell.setCellValue(null == data.getStates() ? "" : data.getStates());// 最终目的国别代码cell = row.createCell(cellNum++);cell.setCellValue(null == data.getLastcountrycode() ? "" : data.getLastcountrycode());}}

实际使用场景

public void exportCountryData(Map<String, Object> queryMap, OutputStream os) {try {//new一个工具类,喜欢做成静态的也行,你们自己修改修改CountryExcelWriter countryExcelWriter = new CountryExcelWriter();//查询出符合业务的数据List<Country> dataList = wlCountryMapper.getCountrys(queryMap);PathUtils pathUtils = new PathUtils();//获取模板的全路径String tempalte = pathUtils.getWEBINFPath() + "resource"  + File.separator+ "countryList.xlsx";//把查询出来的数据传入,把模板全路径传入Workbook wb = countryExcelWriter.exportDataTem(dataList, tempalte);//写到对应的输出流,一般来说都是response的流,用于下载。看各自的业务了wb.write(os);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}

JAVA使用POI写入excel 工具类【通用】相关推荐

  1. Java基于POI读取Excel工具类

    为什么为封装此工具类? 由于公司供应链部门业务需要,对Excel处理这块有较为严苛的要求.为了提高开发效率,从实际项目出发封装了通用自定义读取Excel工具类. 功能概述 支持读取全部excel数据 ...

  2. Java中 POI读取Excel工具类

    直接上代码 pom文件需要导入这些依赖 org.apache.poi poi-ooxml 3.9 org.apache.poi poi-ooxml-schemas 3.9 org.apache.poi ...

  3. 自定义POI的excel工具类-xls-xlsx

    自定义POI的excel工具类-xls-xlsx 使用jdk8(java8)实现Excel导出,随意切换 xls和xlsx.自己只是封装了比较常用方法,07版生成还有bug.ε=(´ο`*)))唉 j ...

  4. java 兼容excel_Java解析Excel工具类(兼容xls和xlsx)

    依赖jar org.apache.poi poi-ooxml 4.0.1 ExcelUtils.java package javax.utils; import java.io.File; impor ...

  5. 自己封装的poi操作Excel工具类

    在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完成的功能是:读取Excel.汇总Exc ...

  6. POI导出Excel工具类(简单看完就会)

    (一)POI介绍 Apache POI是Apache软件基金会的开源项目,POI提供API给Java程序对Microsoft Office格式档案读和写的功能. .NET的开发人员则可以利用NPOI ...

  7. 使用回调方式写POI导入excel工具类

    场景是这样的:为了做一个excel导入的功能,为了尽可能的写一个通用的工具类,将与poi有关的东西都封装起来,以便以其他人员只用关心自己的业务,不用和poi打交道. 写到最后,现在还是会有poi的东西 ...

  8. java按照模板导出Excel工具类

    准备模板: 模板中使用jxls表达式,详细的jxls表达式使用可以到网上查找.一下给出简单的说明 <jx:forEach items="${results.list}" va ...

  9. poi读取excel工具类

    1.添加依赖 <dependency><groupId>org.apache.poi</groupId><artifactId>poi</arti ...

最新文章

  1. 规格选项表管理之更新规格选项表数据
  2. CoordinatorLayout、AppBarLayout、Toolbar使用详解
  3. 前台使用三元运算符判断显示
  4. 点击列表高亮_HTML5 标签列表
  5. oracle 10G windows启动与关闭另类方法
  6. 利用Python随机或暴力生成密码
  7. 性能测试中脚本怎么写_脚本在流程中的性能影响
  8. poj Going from u to v or from v to u? 强联通缩点+拓扑排序(或搜索)
  9. sqlmap源码阅读_listTamperingFunctions和_setTamperingFunctions
  10. CSDN下载频道,免积分免登录下载文件方法
  11. 获取Android APP的包名
  12. Java面向对象三大特性
  13. [ZZ]在争议中逐渐成熟 电力线通信填平信息鸿沟
  14. MMA7660传感器使用心得
  15. 【更改google chrome浏览器路径的方法】
  16. idea中加入插入当前系统日期快捷键
  17. 科技大停滞--过去已逝,未来未来
  18. Java尚能饭否?10月编程排行榜告诉你!
  19. 怎样学习Peoplesoft -byl vhonglei
  20. 易宝典——玩转O365中的EXO服务 之五十 如何知道微软管理员进行了哪些操作

热门文章

  1. 迅雷5.5.4.268去广告版
  2. Hive Select 查询数据
  3. QT实现简单计算器功能
  4. 详细讲解网络协议:TCP和UDP什么区别?
  5. nodejs 如何检测端口可用性
  6. nRF52840/nRF52832 低功耗的测试工程
  7. 使用Matlab计算趋势
  8. 区块链+社交:如何解决行业痛点?改变社交媒体?
  9. [Python] OpenCV 摄像头黑边问题 - 彻底解决
  10. 对计算机学院祝福语,祝福学校发展的祝福语(精选60句)