例如:导出用户信息到excel

引入对应资源库:

// 我使用的gradle,使用maven的去maven repository复制implementation 'org.apache.poi:poi:4.1.2'implementation 'org.apache.poi:poi-ooxml:4.1.2'implementation 'org.apache.poi:poi-ooxml-schemas:4.1.2'
//controller层
@GetMapping("/exportuserexcel")public void exportUserExcel(HttpServletResponse response){userService.exportUserExcel(response);}
 //service层public void exportUserExcel(HttpServletResponse response) {//查出想要导出的用户信息List<UserDto> userList= UserList;//定义导出的文件名String fileName = excelFileNameBuffer();exportDetail(response,fileName,userList);}public String excelFileNameBuffer(){return "xxxx_" + TimeUtils.formatTimeToDay(new Date()) +"_" +TimeUtils.formatTimeToSecond(new Date()) +".xlsx";}public void exportDetail(HttpServletResponse response,String fileName,List<UserDto> userList) {response.reset();try {response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), StandardCharsets.ISO_8859_1));} catch (UnsupportedEncodingException e) {LOGGER.error(e.getMessage(),e);}response.setContentType("application/vnd.ms-excel;charset=UTF-8");response.setHeader("Pragma", "no-cache");response.setHeader("Cache-Control", "no-cache");response.setDateHeader("Expires", 0);XSSFWorkbook workbook;try {workbook = exportExcelInfo(userList);OutputStream output;output = response.getOutputStream();BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);bufferedOutPut.flush();workbook.write(bufferedOutPut);bufferedOutPut.close();}catch (Exception e){LOGGER.error(e.getMessage(),e);}}public XSSFWorkbook exportExcelInfo(List<UserDto> list) {List<ExcelBean> excel=new ArrayList<>();Map<Integer,List<ExcelBean>> map=new LinkedHashMap<>();XSSFWorkbook xssfWorkbook = null;//第一个参数为表头,第二个参数为要取的字段excel.add(new ExcelBean("Name","username",0));excel.add(new ExcelBean("Type","usertypename",0));excel.add(new ExcelBean("Full Name","fullname",0));excel.add(new ExcelBean("Email","email",0));map.put(0, excel);try {xssfWorkbook = ExcelUtil.createExcelFile(UserDto.class, list, map, "UserInfo");} catch (Exception e) {LOGGER.error(e.getMessage(),e);}return xssfWorkbook;}

以下工具类可直接使用:

//工具类
import org.apache.poi.xssf.usermodel.XSSFCellStyle;public class ExcelBean implements  java.io.Serializable{private String headTextName; //列头(标题)名private String propertyName; //对应字段名private Integer cols; //合并单元格数private XSSFCellStyle cellStyle;public String getHeadTextName() {return headTextName;}public void setHeadTextName(String headTextName) {this.headTextName = headTextName;}public String getPropertyName() {return propertyName;}public void setPropertyName(String propertyName) {this.propertyName = propertyName;}public Integer getCols() {return cols;}public void setCols(Integer cols) {this.cols = cols;}public XSSFCellStyle getCellStyle() {return cellStyle;}public void setCellStyle(XSSFCellStyle cellStyle) {this.cellStyle = cellStyle;}public ExcelBean(){}public ExcelBean(String headTextName, Integer cols) {this.headTextName = headTextName;this.cols = cols;}public ExcelBean(String headTextName, String propertyName){this.headTextName = headTextName;this.propertyName = propertyName;}public ExcelBean(String headTextName, String propertyName, Integer cols) {super();this.headTextName = headTextName;this.propertyName = propertyName;this.cols = cols;}}
//工具类
import org.apache.http.client.utils.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;public class ExcelUtil {private final static String excel2003L =".xls";    //2003- 版本的excelprivate final static String excel2007U =".xlsx";   //2007+ 版本的excel/*** Excel导入*/public static  List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{List<List<Object>> list = null;//创建Excel工作薄Workbook work = getWorkbook(in,fileName);if(null == work){throw new Exception("创建Excel工作薄为空!");}Sheet sheet = null;Row row = null;Cell cell = null;list = new ArrayList<List<Object>>();//遍历Excel中所有的sheetfor (int i = 0; i < work.getNumberOfSheets(); i++) {sheet = work.getSheetAt(i);if(sheet==null){continue;}//遍历当前sheet中的所有行//包涵头部,所以要小于等于最后一列数,这里也可以在初始值加上头部行数,以便跳过头部for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {//读取一行row = sheet.getRow(j);//去掉空行和表头if(row==null||row.getFirstCellNum()==j){continue;}//遍历所有的列List<Object> li = new ArrayList<Object>();for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {cell = row.getCell(y);li.add(getCellValue(cell));}list.add(li);}}return list;}/*** 描述:根据文件后缀,自适应上传文件的版本*/public static  Workbook getWorkbook(InputStream inStr, String fileName) throws Exception{Workbook wb = null;String fileType = fileName.substring(fileName.lastIndexOf("."));if(excel2003L.equals(fileType)){wb = new HSSFWorkbook(inStr);  //2003-}else if(excel2007U.equals(fileType)){wb = new XSSFWorkbook(inStr);  //2007+}else{throw new Exception("解析的文件格式有误!");}return wb;}/*** 描述:对表格中数值进行格式化*/public static  Object getCellValue(Cell cell){Object value = null;DecimalFormat df = new DecimalFormat("0");  //格式化字符类型的数字SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");  //日期格式化DecimalFormat df2 = new DecimalFormat("0.00");  //格式化数字switch (cell.getCellType()) {case STRING:value = cell.getRichStringCellValue().getString();break;case NUMERIC:if("General".equals(cell.getCellStyle().getDataFormatString())){value = df.format(cell.getNumericCellValue());}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){value = sdf.format(cell.getDateCellValue());}else{value = df2.format(cell.getNumericCellValue());}break;case BOOLEAN:value = cell.getBooleanCellValue();break;case BLANK:value = "";break;default:break;}return value;}/*** 导入Excel表结束* 导出Excel表开始* @param sheetName 工作簿名称* @param clazz  数据源model类型* @param objs   excel标题列以及对应model字段名* @param map  标题列行数以及cell字体样式*/public static XSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<ExcelBean>> map, String sheetName) throwsIllegalArgumentException,IllegalAccessException, InvocationTargetException,ClassNotFoundException, IntrospectionException, ParseException {// 创建新的Excel工作簿XSSFWorkbook workbook = new XSSFWorkbook();// 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称XSSFSheet sheet = workbook.createSheet(sheetName);// 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;createFont(workbook); //字体样式createTableHeader(sheet, map); //创建标题(头)createTableRows(sheet, map, objs, clazz); //创建内容return workbook;}private static XSSFCellStyle fontStyle;private static XSSFCellStyle fontStyle2;public static void createFont(XSSFWorkbook workbook) {// 表头fontStyle = workbook.createCellStyle();XSSFFont font1 = workbook.createFont();//font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);font1.setFontName("黑体");font1.setFontHeightInPoints((short) 14);// 设置字体大小fontStyle.setFont(font1);
//        fontStyle.setBorderBottom(HorizontalAlignment.BORDER_THIN); // 下边框
//        fontStyle.setBorderLeft(HorizontalAlignment.BORDER_THIN);// 左边框
//        fontStyle.setBorderTop(HorizontalAlignment.BORDER_THIN);// 上边框
//        fontStyle.setBorderRight(HorizontalAlignment.BORDER_THIN);// 右边框fontStyle.setAlignment(HorizontalAlignment.LEFT); // 居左// 内容fontStyle2=workbook.createCellStyle();XSSFFont font2 = workbook.createFont();font2.setFontName("宋体");font2.setFontHeightInPoints((short) 10);// 设置字体大小fontStyle2.setFont(font2);
//        fontStyle2.setBorderBottom(HorizontalAlignment.BORDER_THIN); // 下边框
//        fontStyle2.setBorderLeft(HorizontalAlignment.BORDER_THIN);// 左边框
//        fontStyle2.setBorderTop(HorizontalAlignment.BORDER_THIN);// 上边框
//        fontStyle2.setBorderRight(HorizontalAlignment.BORDER_THIN);// 右边框fontStyle2.setAlignment(HorizontalAlignment.LEFT); // 居左}/*** 根据ExcelMapping 生成列头(多行列头)** @param sheet 工作簿* @param map 每行每个单元格对应的列头信息*/public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {int startIndex=0;//cell起始位置int endIndex=0;//cell终止位置for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {XSSFRow row = sheet.createRow(entry.getKey());List<ExcelBean> excels = entry.getValue();for (int x = 0; x < excels.size(); x++) {//合并单元格if(excels.get(x).getCols()>1){MergeCells(sheet,x,startIndex,endIndex,excels,row);}else{XSSFCell cell = row.createCell(x);cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容if (excels.get(x).getCellStyle() != null) {cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式}cell.setCellStyle(fontStyle);}}}}public static void MergeCells(XSSFSheet sheet, int x, int startIndex, int endIndex, List<ExcelBean> excels, XSSFRow row){if(x==0){endIndex+=excels.get(x).getCols()-1;CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);sheet.addMergedRegion(range);startIndex+=excels.get(x).getCols();}else{endIndex+=excels.get(x).getCols();CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);sheet.addMergedRegion(range);startIndex+=excels.get(x).getCols();}XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容if (excels.get(x).getCellStyle() != null) {cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式}cell.setCellStyle(fontStyle);}public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz)throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException {int rowindex = map.size();int maxKey = 0;List<ExcelBean> ems = new ArrayList<>();for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {if (entry.getKey() > maxKey) {maxKey = entry.getKey();}}ems = map.get(maxKey);List<Integer> widths = new ArrayList<Integer>(ems.size());createTableRowsLogicLoop(sheet,objs,rowindex,ems,clazz,widths);// 设置列宽for (int index = 0; index < widths.size(); index++) {Integer width = widths.get(index);width = width < 2500 ? 2500 : width + 300;width = width > 10000 ? 10000 + 300 : width + 300;sheet.setColumnWidth(index, width);}}public static void createTableRowsLogicLoop(XSSFSheet sheet, List objs, int rowindex, List<ExcelBean> ems, Class clazz, List<Integer> widths) throws InvocationTargetException, IllegalAccessException, IntrospectionException {for (Object obj : objs) {XSSFRow row = sheet.createRow(rowindex);for (int i = 0; i < ems.size(); i++) {ExcelBean em = (ExcelBean) ems.get(i);PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);// 获得get方法Method getMethod = pd.getReadMethod();Object rtn = getMethod.invoke(obj);String value = "";value = typeCast(rtn,value);XSSFCell cell = row.createCell(i);cell.setCellValue(value);cell.setCellType(CellType.STRING);cell.setCellStyle(fontStyle2);int width = value.getBytes().length * 300;// 获得最大列宽if (widths.size() <= i) {// 还未设置,设置当前widths.add(width);continue;}if (width > widths.get(i)) {// 比原来大,更新数据widths.set(i, width);}}rowindex++;}}public static String typeCast(Object rtn, String value){if (rtn != null) {// 如果是日期类型进行转换if (rtn instanceof Date) {value = DateUtils.formatDate((Date)rtn,"yyyy-MM-dd");} else if(rtn instanceof BigDecimal){NumberFormat nf = new DecimalFormat("#,##0.00");value=nf.format((BigDecimal)rtn).toString();} else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){value="--";}else {value = rtn.toString();}}return value;}
}

导出样式:

java使用poi操作excel,写入excel数据并下载相关推荐

  1. Java使用POI读取和写入Excel指南

    Java使用POI读取和写入Excel指南 做项目时经常有通过程序读取Excel数据,或是创建新的Excel并写入数据的需求: 网上很多经验教程里使用的POI版本都比较老了,一些API在新版里已经废弃 ...

  2. Java实战—POI操作Excel文档、读取、写入、合并单元格

    一.POI项目简介 POI全称 Poor Obfuscation Implementation,利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:http: ...

  3. java用poi操作excel,2003,2007,2010

    原文: [url]http://happyqing.iteye.com/blog/1965570[/url] [color=red]通过POI统一读取Excel文件[/color](兼容97-2003 ...

  4. JAVA使用POI操作Excel表,XSSF(xlsx)和HSSF(xls)

    JAVA使用POI操作Excel表,XSSF(xlsx)和HSSF(xls) *** POI的结构: ---*HSSF - 提供读写Microsoft Excel格式档案的功能. ---*XSSF - ...

  5. execle java,Java使用POI操作Excel

    Java使用POI操作Excel 1. POI操作Excel 1.1. 依赖 org.apache.poi poi 4.1.0 org.apache.poi poi-ooxml 4.1.0 org.a ...

  6. java使用poi操作excel删除一整行

    java使用poi操作excel删除一整行 需求1:删除excel表格第4行 代码示例: sheet.shiftRows(4, sheet.getLastRowNum(),-1); 第一个参数为行数( ...

  7. Java使用poi操作excel注意事项

    Java使用poi操作excel注意事项 1.如果只需要获取sheet信息,用流模式打开文件即可获取,消耗内存少 2.上传的文件需要校验,防止Excel包含异常的缓存文件,缓存文件可能会有几百兆,会瞬 ...

  8. java使用poi操作world生成饼图,柱状图,折线图,组合图:二

    java使用poi操作world生成饼图,柱状图,折线图,组合图:二 上文和问题链接 直接上代码 maven 测试类:单图表(入口) 测试类:组合图表(入口) 工具类:组合数据类 工具类:枚举解析图表 ...

  9. java使用poi操作world生成饼图,柱状图,折线图,组合图:一

    java使用poi操作world生成饼图,柱状图,折线图,组合图:一 下文和问题链接 开发前准备 准备模板 模板下载地址百度云盘:cvod 本文可用操作 组合图操作 模板效果对比填充后的效果 饼图 模 ...

  10. Java使用poi操作ppt

    Java使用poi操作ppt https://editor.csdn.net/md/?articleId=117926694 上一篇中写了操作文本框和插入图片 这一篇主要是如何在有模板的情况下如替换文 ...

最新文章

  1. server vscode中的live_太方便了!这款神器能在浏览器中运行 VS Code,随时随地写代码...
  2. 电视信号——行场同步
  3. 人脸对齐--Unconstrained Face Alignment without Face Detection
  4. VTK:可视化之Camera
  5. MarkDown页面添加锚点,跳转到本页指定位置
  6. 常用音频软件:Cool edit pro
  7. (05)System Verilog 组合逻辑与时序逻辑区别
  8. 使用Xamarin在Visual Studio中开发Android应用
  9. HDU2567 寻梦【输入输出流+水题】
  10. 自学python能找到工作吗-学习Python真的能找到工作吗?
  11. MongoDB University课程M103 Basic Cluster Administration 学习笔记
  12. Android 进阶自定义View(5)图表统计PieChartView圆饼图的实现
  13. 树莓派 树莓派 编c++_如何建立一个树莓派冰箱的冷冻监视器
  14. PID tuning guide
  15. 如何利用工具低成本构建阿里云灾备方案?
  16. EXCEL公式-文本型数据转换为数值型数据
  17. 高鸿业微观经济学第7版笔记和课后习题答案
  18. 恢复出厂设置android手机号码,安卓手机恢复出厂设置会怎么样?
  19. Android函数响应式编程——RxJava最快速度入门
  20. 2015-4-11更新的pdf

热门文章

  1. 一文解决,oracle显示ORA-01017
  2. 哪个软件可以用来python编程_python编程用哪个软件
  3. 乔布斯去世衍生多种周边产品(支持乔布斯请顶)
  4. 破解邻居家电脑wifi 密码
  5. 【golang】golang初始化项目(iris下载与使用)
  6. 2023 小微支付服务商系统开源源码
  7. x265-1.7版本-encoder/frameencoder.h注释
  8. 游戏引擎开发技术栈总结(自用)
  9. ecmall 连接mysql服务器失败_ecmall ECMall的MySQL数据库调用
  10. mysql服务器cpu爆满解决办法