poi导出excel,基于模板的比较简单,这个列是动态的,所已选择不基于模板的,相对复杂些,要设置样式。包括:设置列宽、设置字体、设置边框

package com.urthink.jxsh.util;import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;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.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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;/*** 导出excel* @author happyqing* @date 2017-09-18*/
public class ExcelExport {/*** 导出excel* @param list                数据列表 List<E> 实体类列表* @param headers           列标题,以英文逗号分割,必传* @param includes      属性,以英文逗号分割,必传* @param filePath           导出文件全路径* @param sheetName          sheet名称:sheet1* @param dataPattern      日期格式:yyyy-MM-dd HH:mm:ss* @throws Exception     另一个程序正在使用此文件,进程无法访问*/public static <E> void exportListEntity(List<E> list, String headers, String includes, String filePath, String sheetName, String dataPattern) throws Exception{//工作簿Workbook wb;// 创建模板工作表if (filePath.endsWith(".xls")) {wb = new HSSFWorkbook();} else {//templatewb = new XSSFWorkbook(new FileInputStream(filePath));//wb = new XSSFWorkbook();wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出}String[] headerArr = headers.split(",");String[] includeArr = includes.split(",");List<String> includeList = Arrays.asList(includeArr);;//字体Font font = wb.createFont();   //font.setFontHeightInPoints((short)14);   //font.setColor(IndexedColors.DARK_BLUE.getIndex());   font.setBoldweight(Font.BOLDWEIGHT_BOLD);//样式CellStyle styleBOLD = createBorderedStyle(wb);styleBOLD.setFont(font);styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);styleBOLD.setWrapText(false); //自动换行//样式CellStyle styleWrap = createBorderedStyle(wb);styleWrap.setWrapText(false);styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);//表Sheet sheet = wb.createSheet(sheetName);//列宽//sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度//sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);//行Row row = sheet.createRow(0);//单元格Cell cell;//写入标题行for(int i=0; i<headerArr.length; i++){cell = row.createCell(i);cell.setCellValue(headerArr[i]);cell.setCellStyle(styleBOLD);}//写入数据E e;           //实体类Field[] fields;    //属性数组Field field;  //属性Object value;   //属性值DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ssfor(int i=0; i<list.size(); i++){row = sheet.createRow(i+1);e = list.get(i);// 利用反射,获取属性数组fields = e.getClass().getDeclaredFields();for(int f=0,c=0; f<fields.length; f++){field = fields[f];if(includeList.contains(field.getName())){cell = row.createCell(c);cell.setCellStyle(styleWrap);//cell.setCellType(Cell.CELL_TYPE_STRING);//field.getName();//field.getType();field.setAccessible(true);  //设置些属性是可以访问的value = field.get(e);     //得到此属性的值//Byte,Short,Int,Long,Float,Double,Boolean,Char, String,Date,BigDecimal,byte[]//cell.setCellValue: boolean,Calendar,Date,double,RichTextString,Stringif(value==null){} else if (value instanceof Date){  cell.setCellValue(dtf.format((Date)value));} else {cell.setCellValue(value.toString());}c++;}}}//写入文件FileOutputStream fOut = new FileOutputStream(filePath);wb.write(fOut);}/*** 导出excel* @param list               数据列表 List<Map<String, Object>>* @param headers         列标题,以英文逗号分割,必传* @param includes          字段名,以英文逗号分割,必传* @param filePath          导出文件全路径* @param sheetName          sheet名称:sheet1* @param dataPattern      日期格式:yyyy-MM-dd HH:mm:ss* @throws Exception     另一个程序正在使用此文件,进程无法访问*/public static void exportListMap(List<Map<String, Object>> list, String headers, String includes, String filePath, String sheetName, String dataPattern) throws Exception{//工作簿Workbook wb;// 创建模板工作表if (filePath.endsWith(".xls")) {wb = new HSSFWorkbook();} else {//templatewb = new XSSFWorkbook(new FileInputStream(filePath));//wb = new XSSFWorkbook();wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出}String[] headerArr = headers.split(",");String[] includeArr = includes.split(",");//字体Font font = wb.createFont();   //font.setFontHeightInPoints((short)14);   //font.setColor(IndexedColors.DARK_BLUE.getIndex());   font.setBoldweight(Font.BOLDWEIGHT_BOLD);//样式CellStyle styleBOLD = createBorderedStyle(wb);styleBOLD.setFont(font);styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);styleBOLD.setWrapText(false); //自动换行//样式CellStyle styleWrap = createBorderedStyle(wb);styleWrap.setWrapText(false);styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);//表Sheet sheet = wb.createSheet(sheetName);//列宽//sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度//sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);//行Row row = sheet.createRow(0);//单元格Cell cell;//写入标题行for(int i=0; i<headerArr.length; i++){cell = row.createCell(i);cell.setCellValue(headerArr[i]);cell.setCellStyle(styleBOLD);}Map rowMap;          //行mapString fieldName; //字段名Object value;      //属性值DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ssfor(int i=0; i<list.size(); i++){row = sheet.createRow(i+1);rowMap = list.get(i);for(int f=0,c=0; f<includeArr.length; f++){fieldName = includeArr[f];cell = row.createCell(c);cell.setCellStyle(styleWrap);value = rowMap.get(fieldName);        //得到此字段的值if(value==null){} else if (value instanceof Date){  cell.setCellValue(dtf.format((Date)value));} else {cell.setCellValue(value.toString());}c++;}}//写入文件FileOutputStream fOut = new FileOutputStream(filePath);wb.write(fOut);}/*** 导出excel* @param list             数据列表 List<List<Object>>,List<Object>是一行数据* @param headers         列标题,以英文逗号分割,必传* @param filePath          导出文件全路径* @param sheetName          sheet名称:sheet1* @param dataPattern      日期格式:yyyy-MM-dd HH:mm:ss* @throws Exception     另一个程序正在使用此文件,进程无法访问*/public static void exportListList(List<List<Object>> list, String headers, String filePath, String sheetName, String dataPattern) throws Exception{//工作簿Workbook wb;// 创建模板工作表if (filePath.endsWith(".xls")) {wb = new HSSFWorkbook();} else {//templatewb = new XSSFWorkbook(new FileInputStream(filePath));//wb = new XSSFWorkbook();wb = new SXSSFWorkbook(1000); //大于1000行时会把之前的行写入硬盘,解决内存溢出}String[] headerArr = headers.split(",");//字体Font font = wb.createFont();   //font.setFontHeightInPoints((short)14);   //font.setColor(IndexedColors.DARK_BLUE.getIndex());   font.setBoldweight(Font.BOLDWEIGHT_BOLD);//样式CellStyle styleBOLD = createBorderedStyle(wb);styleBOLD.setFont(font);styleBOLD.setVerticalAlignment(CellStyle.VERTICAL_CENTER);styleBOLD.setWrapText(false); //自动换行//样式CellStyle styleWrap = createBorderedStyle(wb);styleWrap.setWrapText(false);styleWrap.setVerticalAlignment(CellStyle.VERTICAL_TOP);//表Sheet sheet = wb.createSheet(sheetName);//列宽//sheet.autoSizeColumn(( short ) 0 ); // 调整第一列宽度//sheet.SetColumnWidth(1, 50 * 256);  //设置列宽,50个字符宽度。宽度参数为1/256,故乘以256,中文的要再乘以2
//        sheet.setColumnWidth(0, 3000);//行Row row = sheet.createRow(0);//单元格Cell cell;//写入标题行for(int i=0; i<headerArr.length; i++){cell = row.createCell(i);cell.setCellValue(headerArr[i]);cell.setCellStyle(styleBOLD);}List<Object> dataRow;Object value; //属性值DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ssfor(int i=0; i<list.size(); i++){dataRow = list.get(i);row = sheet.createRow(i+1);for(int j=0; j<dataRow.size(); j++){cell = row.createCell(j);cell.setCellStyle(styleWrap);//cell.setCellType(Cell.CELL_TYPE_STRING);value = dataRow.get(j);if(value==null){} else if (value instanceof Date){  cell.setCellValue(dtf.format((Date)value));} else {cell.setCellValue(value.toString());}}}//写入文件FileOutputStream fOut = new FileOutputStream(filePath);wb.write(fOut);}private static CellStyle createBorderedStyle(Workbook wb){   CellStyle style = wb.createCellStyle();   style.setBorderRight(CellStyle.BORDER_THIN);   style.setRightBorderColor(IndexedColors.BLACK.getIndex());   style.setBorderBottom(CellStyle.BORDER_THIN);   style.setBottomBorderColor(IndexedColors.BLACK.getIndex());   style.setBorderLeft(CellStyle.BORDER_THIN);   style.setLeftBorderColor(IndexedColors.BLACK.getIndex());   style.setBorderTop(CellStyle.BORDER_THIN);   style.setTopBorderColor(IndexedColors.BLACK.getIndex());   return style;   }
}

得到单元格的字符串内容,注意:有的excel里有隐藏列

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import org.apache.poi.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.DateUtil;

// 得到单元格的字符串内容public static String getCellValue(Cell cell) {DecimalFormat df = new DecimalFormat("#");if (cell == null)return "";switch (cell.getCellType()) {case Cell.CELL_TYPE_NUMERIC:if (DateUtil.isCellDateFormatted(cell)) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");return sdf.format(cell.getDateCellValue()).toString();// return sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())).toString();}return df.format(cell.getNumericCellValue());case Cell.CELL_TYPE_STRING:// System.out.println(cell.getStringCellValue());return cell.getStringCellValue();case Cell.CELL_TYPE_FORMULA:return cell.getCellFormula();case Cell.CELL_TYPE_BLANK:return "";case Cell.CELL_TYPE_BOOLEAN:return cell.getBooleanCellValue() + "";case Cell.CELL_TYPE_ERROR:return cell.getErrorCellValue() + "";}return "";}

下载片段:

//下载try {fileName= new String(fileName.getBytes("GBK"), "ISO-8859-1");} catch (UnsupportedEncodingException e) {e.printStackTrace();}response.setContentType("application/octet-stream"); //MIME类型//该步是最关键的一步,使用setHeader()方法弹出"是否要保存"的对话框,打引号的部分都是固定的值,不要改变   response.setHeader("Content-disposition","attachment;filename="+fileName);//写入文件wb.write(response.getOutputStream());

参考:

http://www.iteye.com/problems/65838

poi导出excel,不使用模板的相关推荐

  1. poi读取excel多层表头模板写入数据并导出

    poi读取excel多层表头模板写入数据并导出 这两天刚好写excel,写了一份自定义表头的,写了一份模板的,这里展示一份读取excel模板写入数据并导出的 //title excel的名称 head ...

  2. java输出excel 异常处理_使用poi导出Excel,并设定单元格内容类型,抛出异常

    本例子使用的是HSSF,为Excel2003提供处理方案. 设定为输入类型为数值 import org.apache.poi.hssf.usermodel.DVConstraint; import o ...

  3. JAVA POI导出EXCEL设置自定义样式(线框加粗,合并指定行,合计求和,冻结行)

    前面部分是当时查询的记录: 实现Excel文件单元格合并.冻结和文件导出 Workbook wb = new HSSFWorkbook();Sheet sheet = wb.createSheet(& ...

  4. POI导出Excel (满满的干货啊)

    已经实现的POI导出Excel 步骤一:导入依赖 <dependency><groupId>org.apache.poi</groupId><artifact ...

  5. poi导出excel清晰 步骤详解

    [align=center][size=large][color=red][b]poi导出excel清晰 步骤详解[/b][/color][/size][/align] [color=darkblue ...

  6. poi导出Excel文件下载数据

    poi导出Excel文件下载数据 poi上传Excel文件批量的添加数据 : https://blog.csdn.net/kangshifu007/article/details/103149764 ...

  7. JAVA导出Excel通用工具类——第一篇:详细介绍POI 导出excel的多种复杂情况,包括动态设置筛选、动态合并横向(纵向)单元格等多种复杂情况——保姆级别,真的不能再详细了,代码拿来即用)

    JAVA导出Excel通用工具--第一篇:详细介绍POI 导出excel的多种复杂情况,包括动态设置筛选.动态合并横向(纵向)单元格等多种复杂情况--保姆级别,真的不能再详细了,封装通用工具类,代码拿 ...

  8. poi 导出excel实战与word新增行与excel添加背景色与设置单元格边框

    提示:本文尽可能简洁通俗的讲解[poi 导出excel实战] ,如需导入可见文尾 一.导入依赖: <!--Apache poi--><!--xls(03)--><depe ...

  9. 复杂的POI导出Excel表格(多行表头、合并单元格)

    poi导出excel有两种方式: 第一种:从无到有的创建整个excel,通过HSSFWorkbook,HSSFSheet HSSFCell, 等对象一步一步的创建出工作簿,sheet,和单元格,并添加 ...

最新文章

  1. centOS7.4服务器 yum安装 搭建lamp环境
  2. Adobe源码泄漏?3行代码搞定,Flash动画无缝导入Android/iOS/cocos2dx(一)
  3. unknown error 1130,unknown error 1045
  4. transformers库的使用【二】tokenizer的使用,模型的保存自定义
  5. office 2007图标_微软Office 365桌面版新图标开始测试
  6. 钟 docker讲解
  7. Spring-----AOP-----事务
  8. C语言x86汇编指令理解volatile(三十五)
  9. php-mvc模式(2)
  10. 局域网传文件_超好用的文件传输工具!
  11. wp7 XAP部署工具
  12. arm-linux-g++ crypto,在Ubuntu中找不到libcrypto
  13. 151308-48-4,Cyclo(-Gly-Asn-Trp-His-Gly-Thr-Ala-Pro-Asp)-Trp-Val-Tyr-Phe-Ala-His-Leu-Asp-Ile-Ile-Trp
  14. 【LaTeX PPT模板集】Beamer主题与配色使用教程
  15. 论文阅读:Meta-Learning in Neural Networks: A Survey
  16. 正则应用(用户名输入框)
  17. 【洛谷P1605 迷宫】
  18. Jest 常用匹配器
  19. Oracle数据库启停
  20. xp系统扫描仪服务器,通过系统自带的扫描仪向导获取图片(适用于WinXP)

热门文章

  1. ### The error may exist in com/itheima/mapper/UserMapper.xml ### Cause: org.apache.ibatis.builder.Bu
  2. 【图像处理】去雾算法
  3. gecco爬虫初见与综述
  4. 什么是全量备份,增量备份,差异备份?
  5. 真实评测:天玑1000+相当于骁龙什么处理器-联发科天玑1000+处理器相当于骁龙多少
  6. 编译器警告c4996
  7. 用IP段区分境内外用户
  8. 2012年第三届蓝桥杯C组 day11
  9. 【Apache Poi】如何使用poi在word中生成复选框
  10. 用GitChat赚钱的6种方法