码迷,mamicode.com
首页 > 其他好文 > 详细

利用poi导出Excel

时间:2017-01-01 23:56:06      阅读:450      评论:0      收藏:0      [点我收藏+]

标签:ops   cat   horizon   XML   array   field   限制   amp   cas   

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;

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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

//需要的jar包:poi-3.15.jar、poi-ooxml-3.15.jar

/**
* 2002、2003的一个工作簿中最多含有256个工作表,默认情况下是三个工作表,工作表由65536行*256列组成,每行列交叉为一个单位格。
* 2007的无论是工作表个数、工作表列数、行数,都大大突破了这个数据,excel默认的工作薄扩展名为".xlsx",
* 这种格式的文件中每个工作页包含1048576行(Row)*16384列(Column)。EXCEL的帮助文件上说的,理论上sheet是无限个,但受可用内存的限制,
* 你可以试着插入一个新工作表,然后按着F4,就会看见工作表不停的增加,我1G内存,工作表增加到10000个,还能正常进行基本操作 。
*/

/**
*
* Excel导出方法
*@param title Excel标题
*@param headersParams 以字符串"header = param"方式存储元素的List<Striing>;header代表的是表头,param代表的是表头对应的属性
*@param dataList 需要导出Excel数据
*@param sheetMaxCount 每一个sheet的最大存储行数(数量)
*@return Workbook
*@since (此方法开始于哪个版本)0.0.3
*@author yangke
*
*/
public class NextExcelUtil {

/**
* 分sheet导出Excel的情况
* @param title Excel表的标题,如果不存在,则传null
* @param headersParams 表头与属性值的对应关系数组
* @param dataList 导出Excel数据
* @param sheetMaxCount 单个sheet存储数据量最大值
* */
@SuppressWarnings({ "unchecked", "rawtypes", "unused" })
public static <T> Workbook getWorkbook(String title, List<String> headersParams, List<T> dataList, int sheetMaxCount) {
//获取导出总数据量
int count = dataList.size();
//获取要分多少个sheet
int page = count%sheetMaxCount > 0 ? count/sheetMaxCount + 1 : count/sheetMaxCount;
//拆分大的List为多个小的List
List<List> splitList = getSplitList(dataList, sheetMaxCount);
//建表
Workbook wb = new HSSFWorkbook();
for(int i = 0;i < page;i++){
int m = 0;
//创建sheet
Sheet sheet = wb.createSheet();
if(title != null){
wb.setSheetName(i, title+i);
//设置标题
for(int j = 0;j < 2;j++){
Row titleRow = sheet.createRow(i);
for(int k = 0;k < headersParams.size();k++){
Cell titleCell = titleRow.createCell(k);
CellStyle titleStyle = getStyle(wb);
titleCell.setCellStyle(titleStyle);
//标题内容只设置一次就行,且值只能设置在标题所占的位置的首行首列,否则合并单元格时值会被覆盖
if(j == 0 && k == 0){
titleCell.setCellValue(title);
titleCell.setCellStyle(titleStyle);
}
}
}
//合并标题单元格
sheet.addMergedRegion(new CellRangeAddress(0, 1,0,headersParams.size()-1));
m = 2;
}

//获取表头及其对应的属性
String[] headers = new String[headersParams.size()];
String[] params = new String[headersParams.size()];
for(int j = 0;j < headersParams.size();j++){
String[] hsPs = headersParams.get(j).toString().split("=");
headers[j] = hsPs[0];
params[j] = hsPs[1];
}

//设置表头
Row headRow = sheet.createRow(m);
for(int j = 0;j < headers.length;j++){
Cell headerCell = headRow.createCell(j);
headerCell.setCellValue(headers[j]);
}
//获取单个sheet需要填充的数据
List<T> smallList = splitList.get(i);
//给单个sheet填充数据
//获取反射模版
Class clazz = null;
for(int j = 0;j < smallList.size();j++){
clazz = smallList.get(0).getClass();
Row paramRow = sheet.createRow(j + 1 + m);
for(int k = 0;k < params.length;k++){
try {
Field field = clazz.getDeclaredField(params[k]);
Method method = clazz.getMethod(getMethodName(params[k]));
Object obj = method.invoke(smallList.get(j));

Cell paramCell = paramRow.createCell(k);
//判断是否为时间格式
if(obj.getClass() == Date.class){
if(obj != null){
CreationHelper creationHelper = wb.getCreationHelper();
CellStyle dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(
creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
paramCell.setCellStyle(dateStyle);
paramCell.setCellValue((Date)obj);
}else{
paramCell.setCellValue("");
}
}else{
if(obj != null){
paramCell.setCellValue(obj.toString());
}else{
paramCell.setCellValue("");
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
return wb;
}


/**
* 导出单个sheet的Excel
* @param title Excel表的标题,如果不存在,则传null
* @param headersParams 表头与属性值的对应关系数组
* @param dataList 导出Excel数据
* */
@SuppressWarnings({ "rawtypes", "unused", "unchecked" })
public static <T> Workbook getWorkbook(String title,List<String> headersParams,List<T> dataList) {
//建表
Workbook wb = new HSSFWorkbook();
//创建工作簿
Sheet sheet = wb.createSheet();

//设置起始行,默认为0
int m = 0;
//判断是否存在标题
if(title != null){
wb.setSheetName(0, title);
//设置标题
for(int i = 0;i < 2;i++){
Row titleRow = sheet.createRow(i);
for(int j = 0;j < headersParams.size();j++){
Cell titleCell = titleRow.createCell(j);
CellStyle titleStyle = getStyle(wb);
titleCell.setCellStyle(titleStyle);

//标题内容只设置一次就行,且值只能设置在标题所占的位置的首行首列,否则合并单元格时值会被覆盖
if(j == 0 && i == 0){
titleCell.setCellValue(title);
titleCell.setCellStyle(titleStyle);

}

}
}
//合并标题单元格
sheet.addMergedRegion(new CellRangeAddress(0, 1,0,headersParams.size()-1));
m = 2;
}

String[] headers = new String[headersParams.size()];
String[] params = new String[headersParams.size()];
for(int i = 0;i < headersParams.size();i++){
String[] headerParam = headersParams.get(i).split("=");
headers[i] = headerParam[0];
params[i] = headerParam[1];
}
//设置表头
Row headRow = sheet.createRow(m);
for(int i = 0;i < headers.length;i++){
Cell headerCell = headRow.createCell(i);
headerCell.setCellValue(headers[i]);
}
//填入数据
//获取反射模版
Class clazz = null;
if(dataList != null && dataList.size() > 0){
clazz = dataList.get(0).getClass();
for(int i = 0;i < dataList.size();i++){
Row paramRow = sheet.createRow(i + 1 + m);
for(int j = 0;j < params.length;j++){
try {
Cell paramCell = paramRow.createCell(j);
Field field = clazz.getDeclaredField(params[j]);
Method method = clazz.getMethod(getMethodName(params[j]));
Object obj = method.invoke(dataList.get(i));

//判断是否为时间格式
if(obj.getClass() == Date.class){
if(obj != null){
CreationHelper creationHelper = wb.getCreationHelper();
CellStyle dateStyle = wb.createCellStyle();
dateStyle.setDataFormat(
creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
paramCell.setCellStyle(dateStyle);
paramCell.setCellValue((Date)obj);
}else{
paramCell.setCellValue("");
}
}else{
if(obj != null){
paramCell.setCellValue(obj.toString());
}else{
paramCell.setCellValue("");
}
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}

}
}
return wb;
}

/**
*
* 设置标题边框
*@param workbook Excel对象
*@param titleRow 标题行
*@param headersParams 列名属性名,对应关系的List
*@return CellStyle 标题样式
*@since (此方法开始于哪个版本)0.0.3
*@author yk
*
*/
@SuppressWarnings("deprecation")
public static CellStyle getStyle(Workbook wb) {
//创建显示样式
CellStyle style = wb.createCellStyle();
//创建字体样式
Font font = wb.createFont();

font.setFontHeight((short) 280);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);

style.setAlignment(HorizontalAlignment.CENTER);
//设置边框
style.setBorderBottom(CellStyle.BORDER_THIN);
style.setBorderLeft(CellStyle.BORDER_THIN);
style.setBorderRight(CellStyle.BORDER_THIN);
style.setBorderTop(CellStyle.BORDER_THIN);
style.setFont(font);
return style;
}
/*
* 标题样式
*/
@SuppressWarnings("deprecation")
public static <T> CellStyle getTitleStyle(Workbook workbook) {

// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
CellStyle style = workbook.createCellStyle();
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(CellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
return style;

}

/*
* 列头单元格样式
*/
@SuppressWarnings("deprecation")
public CellStyle getColumnTopStyle(Workbook workbook) {

// 设置字体
Font font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(CellStyle.BORDER_THIN);
//设置左边框;
style.setBorderLeft(CellStyle.BORDER_THIN);
//设置右边框;
style.setBorderRight(CellStyle.BORDER_THIN);
//设置顶边框;
style.setBorderTop(CellStyle.BORDER_THIN);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(CellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);

return style;

}

/*
* 列数据信息单元格样式
*/
@SuppressWarnings("deprecation")
public CellStyle getCellStyle(Workbook workbook) {
// 设置字体
Font font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short)10);
//字体加粗
//font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
CellStyle style = workbook.createCellStyle();
//设置底边框;
style.setBorderBottom(CellStyle.BORDER_THIN);
//设置左边框;
style.setBorderLeft(CellStyle.BORDER_THIN);
//设置右边框;
style.setBorderRight(CellStyle.BORDER_THIN);
//设置顶边框;
style.setBorderTop(CellStyle.BORDER_THIN);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

return style;

}

/*
* 获取方法名
* @param 属性名
* */
private static String getMethodName(String fieldName){
return "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
}

}

利用poi导出Excel

标签:ops   cat   horizon   XML   array   field   限制   amp   cas   

原文地址:http://www.cnblogs.com/shenjichenai/p/6241711.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!