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:ss
for(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,String
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<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; //行map
String fieldName; //字段名
Object value; //属性值
DateFormat dtf = new SimpleDateFormat(dataPattern); //yyyy-MM-dd HH:mm:ss
for(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:ss
for(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