POI数据的excel导出

第一步:[引入jar包] [ 版本选择http://mvnrepository.com/ ]

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.17</version>
    </dependency>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.17</version>

    </dependency>

第二步:[ 工具类 ]

package com.kdkj.utils;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
public class ExportExcel {
// 显示的导出表的标题
private String title;
// 导出表的列名
private String[] rowName;
private String title2;
private String[] rowName2;
private List<Object[]> dataList = new ArrayList<Object[]>();
        private List<Object[]> dataList2 = new ArrayList<Object[]>();
// 构造方法,传入要导出的数据
public ExportExcel(String title, String[] rowName, List<Object[]> datalist) {
this.dataList = datalist;
this.rowName = rowName;
this.title = title;
}
// 多个参数的构造方法
public ExportExcel(String title, String[] rowName, String title2,
String[] rowName2, List<Object[]> dataList, List<Object[]> dataList2) {
super();
this.title = title;
this.rowName = rowName;
this.title2 = title2;
this.rowName2 = rowName2;
this.dataList = dataList;
this.dataList2 = dataList2;
}
/**
* 导出Excel数据 每个sheet的最大数据条数是:50000

* @param response
*            导出Excel的响应信息
* @param filename
*            文件名
* @throws Exception
*             异常
*/
public void export(HttpServletResponse response,HttpServletRequest request, String filename)
throws Exception {
String userAgent = request.getHeader("User-Agent"); 
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE浏览器的处理:
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"", filename));
response.setContentType("APPLICATION/OCTET-STREAM");
response.setCharacterEncoding("UTF-8");
// 输出流
OutputStream out = response.getOutputStream();
// 创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
// sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); // 单元格样式对象
int rowsCount = dataList.size();// 总的数据条数
int sheetMaxRowCount = 50000;// 每个sheet的最大数据条数
int sheetIndex = rowsCount / sheetMaxRowCount;
// 遍历每个sheet,并赋值
for (int a = 0; a <= sheetIndex; a++) {
HSSFSheet sheet = workbook.createSheet(title + a); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0,// 合并单元格
(rowName.length - 1)));
cellTiltle.setCellStyle(columnTopStyle);// 设置标题样式
cellTiltle.setCellValue(title);// 设置标题值
int columnNum = rowName.length;// 定义所需列数
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
for (int n = 0; n < columnNum; n++) {
HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);// 获取列头单元格值
cellRowName.setCellValue(text); // 设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
sheet.setColumnWidth(n,
(text.toString().getBytes().length + 8) * 256);// 设置列宽
}
// 每个sheet的初始行号
int sheetRowNum = a * sheetMaxRowCount;
// 最后一个sheet的数据条数
int lastRowCount = rowsCount % sheetMaxRowCount;
if (a == sheetIndex) {
sheetMaxRowCount = lastRowCount;
}
// 将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < sheetMaxRowCount; i++) {
HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数
Object[] obj = dataList.get(sheetRowNum + i);// 遍历每个对象
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = row.createCell(j); // 定义列的单元格
if (j == 0) {// 第一列
cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(sheetRowNum + i + 1);
} else {// 剩余列
cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
cell.setCellValue(obj[j].toString());// 设置单元格的值
} else {
cell.setCellValue("");
}
}
cell.setCellStyle(style); // 设置单元格样式
}
}
}
workbook.write(out);
out.close();
}
public void export2(HttpServletResponse response, String filename)
throws Exception {
// 导出Excel的响应信息
String headStr = "attachment; filename=\""
+ new String(filename.getBytes("UTF-8"), "iso8859-1") + "\"";
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", headStr);
// 输出流
OutputStream out = response.getOutputStream();
// 创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
// sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); // 单元格样式对象
int rowsCount = dataList.size();// 总的数据条数
int sheetMaxRowCount = 50000;// 每个sheet的最大数据条数
int sheetIndex = rowsCount / sheetMaxRowCount;
// 遍历每个sheet,并赋值
for (int a = 0; a <= sheetIndex; a++) {
HSSFSheet sheet = workbook.createSheet(title); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0,// 合并单元格
(rowName.length - 1)));
cellTiltle.setCellStyle(columnTopStyle);// 设置标题样式
cellTiltle.setCellValue(title);// 设置标题值
int columnNum = rowName.length;// 定义所需列数
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
for (int n = 0; n < columnNum; n++) {
HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName[n]);// 获取列头单元格值
cellRowName.setCellValue(text); // 设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
sheet.setColumnWidth(n,
(text.toString().getBytes().length + 8) * 256);// 设置列宽
}
// 每个sheet的初始行号
int sheetRowNum = a * sheetMaxRowCount;
// 最后一个sheet的数据条数
int lastRowCount = rowsCount % sheetMaxRowCount;
if (a == sheetIndex) {
sheetMaxRowCount = lastRowCount;
}
// 将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < sheetMaxRowCount; i++) {
HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数
Object[] obj = dataList.get(sheetRowNum + i);// 遍历每个对象
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = row.createCell(j); // 定义列的单元格
if (j == 0) {// 第一列
cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(sheetRowNum + i + 1);
} else {// 剩余列
cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
cell.setCellValue(obj[j].toString());// 设置单元格的值
} else {
cell.setCellValue("");
}
}
cell.setCellStyle(style); // 设置单元格样式
}
}
}
int rowsCount2 = dataList2.size();// 总的数据条数
int sheetMaxRowCount2 = 50000;// 每个sheet的最大数据条数
int sheetIndex2 = rowsCount2 / sheetMaxRowCount2;
// 遍历每个sheet,并赋值
for (int a = 0; a <= sheetIndex2; a++) {
HSSFSheet sheet = workbook.createSheet(title2); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0,// 合并单元格
(rowName2.length - 1)));
cellTiltle.setCellStyle(columnTopStyle);// 设置标题样式
cellTiltle.setCellValue(title2);// 设置标题值
int columnNum = rowName2.length;// 定义所需列数
HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
for (int n = 0; n < columnNum; n++) {
HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
HSSFRichTextString text = new HSSFRichTextString(rowName2[n]);// 获取列头单元格值
cellRowName.setCellValue(text); // 设置列头单元格的值
cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
sheet.setColumnWidth(n,
(text.toString().getBytes().length + 8) * 256);// 设置列宽
}
// 每个sheet的初始行号
int sheetRowNum = a * sheetMaxRowCount2;
// 最后一个sheet的数据条数
int lastRowCount = rowsCount2 % sheetMaxRowCount2;
if (a == sheetIndex2) {
sheetMaxRowCount2 = lastRowCount;
}
// 将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < sheetMaxRowCount2; i++) {
HSSFRow row = sheet.createRow(i + 3);// 创建所需的行数
Object[] obj = dataList2.get(sheetRowNum + i);// 遍历每个对象
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = row.createCell(j); // 定义列的单元格
if (j == 0) {// 第一列
cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(sheetRowNum + i + 1);
} else {// 剩余列
cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
cell.setCellValue(obj[j].toString());// 设置单元格的值
} else {
cell.setCellValue("");
}
}
cell.setCellStyle(style); // 设置单元格样式
}
}
}
workbook.write(out);
out.close();
}
/*
* 列头单元格样式
*/
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
// 设置字体大小
font.setFontHeightInPoints((short) 11);
// 字体加粗
font.setBold(true);
// 设置字体名字
font.setFontName("Courier New");
// 设置样式;
HSSFCellStyle style = workbook.createCellStyle();
// 设置底边框;
style.setBorderBottom(BorderStyle.THIN);
// 设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 设置左边框;
style.setBorderLeft(BorderStyle.THIN);
// 设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
// 设置右边框;
style.setBorderRight(BorderStyle.THIN);
// 设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
// 设置顶边框;
style.setBorderTop(BorderStyle.THIN);
// 设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
// 设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
/*
* 列数据信息单元格样式
*/
public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
// 设置字体大小
// font.setFontHeightInPoints((short)10);
// 字体加粗
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 设置字体名字
font.setFontName("Courier New");
// 设置样式;
HSSFCellStyle style = workbook.createCellStyle();
// 设置底边框;
style.setBorderBottom(BorderStyle.THIN);
// 设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
// 设置左边框;
style.setBorderLeft(BorderStyle.THIN);
// 设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
// 设置右边框;
style.setBorderRight(BorderStyle.THIN);
// 设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
// 设置顶边框;
style.setBorderTop(BorderStyle.THIN);
// 设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
// 在样式用应用设置的字体;
style.setFont(font);
// 设置自动换行;
style.setWrapText(false);
// 设置水平对齐的样式为居中对齐;
style.setAlignment(HorizontalAlignment.CENTER);
// 设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}

}

第三步:[ controller层 ]

@RequestMapping(value = "exportDate2Excel", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
public void exportDate2Excel(HttpServletResponse response, HttpServletRequest request,HttpSession session) throws Exception {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String filename = "供应商类别.xls";
String title = filename.replace(".xls", "");
String[] rowsName = new String[] { "序号", "类别名","父级", "等级","备注" };
Member user = (Member) session.getAttribute("userInfo");
ScmSupplierCategory bean = new ScmSupplierCategory();
bean.setOrgId(user.getOrgId());
List<ScmSupplierCategory> categoryList = service.getList(bean);
List<Object[]> datalist = new ArrayList<Object[]>();
for (int i = 0; i < categoryList.size(); i++) {
Object[] objs = new Object[rowsName.length];
objs[0] = i + 1;
objs[1] = categoryList.get(i).getCategoryName();
if(Objects.isNull(categoryList.get(i).getParentId())||"".equals(categoryList.get(i).getParentId())) {
objs[2]="根节点 ";
}
objs[2] = service.findById(categoryList.get(i).getParentId()).getCategoryName();
// objs[2] = " ";
objs[3] = categoryList.get(i).getLevel();
objs[4] = categoryList.get(i).getDepict();
datalist.add(objs);
}
ExportExcel ex = new ExportExcel(title, rowsName, datalist);
ex.export(response,request, filename);

}

通过以上的三步走,基本的导出功能实现。


但实际中可能不会这么简单,也会有很多负责的业务逻辑。

例如:

第①步: [ 更改工具类 ]

public void export(HttpServletResponse response,HttpServletRequest request, String filename)
throws Exception {
String userAgent = request.getHeader("User-Agent"); 
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE浏览器的处理:
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition", String.format(
"attachment; filename=\"%s\"", filename));
response.setContentType("APPLICATION/OCTET-STREAM");
response.setCharacterEncoding("UTF-8");

// 输出流
OutputStream out = response.getOutputStream();
// 创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
// sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面 - 可扩展】
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);// 获取列头样式对象
HSSFCellStyle style = this.getStyle(workbook); // 单元格样式对象
int rowsCount = dataList.size();// 总的数据条数
int sheetMaxRowCount = 50000;// 每个sheet的最大数据条数
int sheetIndex = rowsCount / sheetMaxRowCount;
// 遍历每个sheet,并赋值
for (int a = 0; a <= sheetIndex; a++) {
int columnNum = 10;// 定义所需列数
HSSFSheet sheet = workbook.createSheet(title + a); // 创建工作表
// 产生表格标题行
HSSFRow rowm = sheet.createRow(0);
HSSFCell cellTiltle = rowm.createCell(0);
sheet.addMergedRegion(new CellRangeAddress(0, 1, 0,// 合并单元格
(columnNum - 1)));
cellTiltle.setCellStyle(columnTopStyle);// 设置标题样式
cellTiltle.setCellValue(title);// 设置标题值
// HSSFRow rowRowName = sheet.createRow(2); // 在索引2的位置创建行(最顶端的行开始的第二行)
// 将列头设置到sheet的单元格中
// for (int n = 0; n < columnNum; n++) {
// HSSFCell cellRowName = rowRowName.createCell(n); // 创建列头对应个数的单元格
// cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 设置列头单元格的数据类型
// HSSFRichTextString text = new HSSFRichTextString(rowName[n]);// 获取列头单元格值
// cellRowName.setCellValue(text); // 设置列头单元格的值
// cellRowName.setCellStyle(columnTopStyle); // 设置列头单元格样式
// sheet.setColumnWidth(n,
// (text.toString().getBytes().length + 8) * 256);// 设置列宽
// }
// 每个sheet的初始行号
int sheetRowNum = a * sheetMaxRowCount;
// 最后一个sheet的数据条数
int lastRowCount = rowsCount % sheetMaxRowCount;
if (a == sheetIndex) {
sheetMaxRowCount = lastRowCount;
}
// 将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < sheetMaxRowCount; i++) {
HSSFRow row = sheet.createRow(i + 2);// 创建所需的行数
Object[] obj = dataList.get(sheetRowNum + i);// 遍历每个对象
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = row.createCell(j); // 定义列的单元格
// if (j == 0) {// 第一列
// cell = row.createCell(j, HSSFCell.CELL_TYPE_NUMERIC);
// cell.setCellValue(sheetRowNum + i + 1);
// } else {// 剩余列
cell = row.createCell(j, HSSFCell.CELL_TYPE_STRING);
if (!"".equals(obj[j]) && obj[j] != null) {
cell.setCellValue(obj[j].toString());// 设置单元格的值
} else {
cell.setCellValue("");
}
// }
cell.setCellStyle(style); // 设置单元格样式
}
}
}
workbook.write(out);
out.close();

}

第②步:[ controller层 ]

public Result exportDate2Excel(HttpServletResponse response,
HttpServletRequest request) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//定义要输出日期字符串的格式
String filename = "会议表数据导出.xls";
String title = filename.replace(".xls", "");
String[] rowsName = new String[] {};
int length = 10;
List<Object[]> datalist = new ArrayList<Object[]>();
List<Hys> beanList = hysService.selectAll(new Hys());
for (int i = 0; i < beanList.size(); i++) {
Object[] objs = new Object[length];
objs[1] = i + 1;
objs[2] = "会议名称:";
objs[3] = beanList.get(i).getHyName();
objs[4] = "截止时间:";
objs[5] =  sdf.format(beanList.get(i).getDeadline());
objs[6] = "会议状态:";
if (beanList.get(i).getStatus().equals(HysStatus.DISPARK.getCode())) {
objs[7] = HysStatus.DISPARK.getMessage();
} else if (beanList.get(i).getStatus().equals(HysStatus.CLOSE.getCode())) {
objs[7] = HysStatus.CLOSE.getMessage();
} else if (beanList.get(i).getStatus().equals(HysStatus.DISABLED.getCode())) {
objs[7] = HysStatus.DISABLED.getMessage();
}
datalist.add(objs);
List<Task> tasks = beanList.get(0).getTasks();
for (int j = 0; j < tasks.size(); j++) {
Object[] objs1 = new Object[length];
objs1[3] = "任务名称:";
objs1[4] = tasks.get(j).getTaskName();
objs1[6] = "任务描述:";
objs1[7] = tasks.get(j).getDes();
datalist.add(objs1);
List<Assess> assesses = beanList.get(0).getTasks().get(j).getAssesses();
for (int m = 0; m < assesses.size(); m++) {
Object[] objs2 = new Object[length];
if (!StringUtils.isEmpty(assesses.get(m))) {
if (!StringUtils.isEmpty(assesses.get(m).getUser())) {
objs2[4] = "评估人:";
objs2[5] = assesses.get(m).getUser().getName();
}
objs2[7] = "评估时长:";
objs2[8] = assesses.get(m).getAssessTime();
datalist.add(objs2);
}
Object[] objs3 = new Object[length];
objs3[4] = "平均分";
objs3[5] = tasks.get(j).getAvgTaskTime();
datalist.add(objs3);
}
Object[] objs4 = new Object[length];
datalist.add(objs4);
}
}
ExportExcel ex = new ExportExcel(title, rowsName, datalist);
try {
ex.export(response, request, filename);
} catch (Exception e) {
return Result.error("操作失败!");
}
return Result.ok("操作成功!");

}

实现的效果如下:


总结:POI不仅能做导出,也可以做导入。POI的这样写法优点在于可以不使用模板,处理导出。

更多请看下篇博文...

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值