工具类:
public class ExportExcelUtils {
private String title; // 导出表格的表名
private String[] rowName;// 导出表格的列名
private List<Object[]> dataList = new ArrayList<Object[]>(); // 对象数组的List集合
private HttpServletResponse response;
public ExportExcelUtils() {
super();
}
// 传入要导入的数据
public ExportExcelUtils(String title,String[] rowName,List<Object[]> dataList,HttpServletResponse response){
this.title=title;
this.rowName=rowName;
this.dataList=dataList;
this.response = response;
}
// 导出数据
public void exportData(String title,String[] rowName,List<Object[]> dataList,HttpServletResponse response){
try {
/**读取模板
InputStream is = this.getClass().getClassLoader().getResourceAsStream(title);
if(null==is){
is = this.getClass().getResourceAsStream("/templates/"+title);
}
if(null==is){
Resource resource = new ClassPathResource("templates/"+title);
String path = resource.getFile().getPath();
is = new FileInputStream(path);
}
@SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook(is); // 获取一个excel对象
XSSFSheet sheet = workbook.getSheetAt(0); // 获取表格
**/
HSSFWorkbook workbook =new HSSFWorkbook(); // 创建一个excel对象
HSSFSheet sheet =workbook.createSheet(title); // 创建表格
// 产生表格标题行
HSSFRow rowm =sheet.createRow(0); // 行
HSSFCell cellTiltle =rowm.createCell(0); // 单元格
// sheet样式定义
HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook); // 头样式
HSSFCellStyle style = this.getStyle(workbook); // 单元格样式
/**
* 参数说明
* 从0开始 第一行 第一列 都是从角标0开始
* 行 列 行列 (0,0,0,5) 合并第一行 第一列 到第一行 第六列
* 起始行,起始列,结束行,结束列
*
* new Region() 这个方法使过时的
*/
// 合并第一行的所有列
sheet.addMergedRegion(new CellRangeAddress(0, (short) 0, 0, (short) (rowName.length-1)));
cellTiltle.setCellStyle(columnTopStyle);
cellTiltle.setCellValue(title);
int columnNum = rowName.length; // 表格列的长度
HSSFRow rowRowName = sheet.createRow(1); // 在第二行创建行
HSSFCellStyle cells =workbook.createCellStyle();
cells.setBottomBorderColor(HSSFColor.BLACK.index);
rowRowName.setRowStyle(cells);
// 循环 将列名放进去
for (int i = 0; i < columnNum; i++) {
HSSFCell cellRowName = rowRowName.createCell((int)i);
cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING); // 单元格类型
HSSFRichTextString text = new HSSFRichTextString(rowName[i]); // 得到列的值
cellRowName.setCellValue(text); // 设置列的值
cellRowName.setCellStyle(columnTopStyle); // 样式
}
// 将查询到的数据设置到对应的单元格中
for (int i = 0; i < dataList.size(); i++) {
Object[] obj = dataList.get(i);//遍历每个对象
HSSFRow row = sheet.createRow(i+2);//创建所需的行数
for (int j = 0; j < obj.length; j++) {
HSSFCell cell = null; //设置单元格的数据类型
// if(j==0){
// // 第一列设置为序号
// cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
// cell.setCellValue(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); // 样式
}
}
// 让列宽随着导出的列长自动适应
for (int j = 0; j < rowName.length; j++) {
sheet.autoSizeColumn((short)j); //调整第一列宽度
}
if(workbook !=null){
try
{
// excel 表文件名
String fileName = title + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
/*FileOutputStream fOut = new FileOutputStream(new File("E:\\"+fileName)); //创建xls文件,无内容 0字节
workbook.write(fOut); //写内容,xls文件已经可以打开
fOut.flush(); //刷新缓冲区
fOut.close();*/
ByteArrayOutputStream os = new ByteArrayOutputStream();
// 写入数据
workbook.write(os);
// 刷新
os.flush();
download(os, response, fileName);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
response.setContentType("application/octet-stream;charset=utf-8");
returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1")); //保存的文件名,必须和页面编码一致,否则乱码
response.addHeader("Content-Disposition", "attachment;filename=" + returnName);
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream outputstream = response.getOutputStream(); //取得输出流
byteArrayOutputStream.writeTo(outputstream); //写到输出流
byteArrayOutputStream.close(); //关闭
outputstream.flush(); //刷数据
}
public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
// 设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
font.setFontHeightInPoints((short)11);
//字体加粗
// font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//设置字体名字
font.setFontName("Courier New");
//设置样式;
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框;
// style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
// style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
// style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
// style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
// style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
// style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
// style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
// style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_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(HSSFCellStyle.BORDER_THIN);
//设置底边框颜色;
style.setBottomBorderColor(HSSFColor.BLACK.index);
//设置左边框;
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
//设置左边框颜色;
style.setLeftBorderColor(HSSFColor.BLACK.index);
//设置右边框;
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
//设置右边框颜色;
style.setRightBorderColor(HSSFColor.BLACK.index);
//设置顶边框;
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
//设置顶边框颜色;
style.setTopBorderColor(HSSFColor.BLACK.index);
//在样式用应用设置的字体;
style.setFont(font);
//设置自动换行;
style.setWrapText(false);
//设置水平对齐的样式为居中对齐;
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//设置垂直对齐的样式为居中对齐;
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
return style;
}
// 画线
private void setLine(HSSFWorkbook wb, HSSFPatriarch patriarch, int iRowStart, int iColStart, int iRowStop, int iColStop) {
HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 0, (short) (iColStart), iRowStart, (short) (iColStop), iRowStop);
HSSFSimpleShape lineShape = patriarch.createSimpleShape(anchor);
lineShape.setShapeType(HSSFSimpleShape.OBJECT_TYPE_LINE);
}
}
使用:
public void export4(String status) {
String title = "PublishedProcessTraining.xlsx";
String[] rowName = { "流程编码", "流程名称", "版本", "PO", "BPO", "上传时间", "描述",
"状态" };
List<Object[]> dataList = new ArrayList<>();
List<ModelListReleaseDto> list = this.query(status);
Object[] obj = null;
int index = 1;
if (null != list && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
List<ModelListDocDto> list2 = list.get(i).getDoclist();
if (null != list2 && list2.size() > 0) {
for (int j = 0; j < list2.size(); j++) {
obj = new Object[10];
obj[0] = index;
obj[1] = list.get(i).getCode();
obj[2] = list.get(i).getName();
obj[3] = list.get(i).getVersion();
obj[4] = list.get(i).getBponame();
obj[5] = list.get(i).getUpbponame();
obj[6] = DateUtil.formatDate(list.get(i).getCreateon()
.getTime(), "yyyy-MM-dd HH:mm:ss");
obj[7] = DateUtil.formatDate(list2.get(j).getCreateon()
.getTime(), "yyyy-MM-dd HH:mm:ss");
obj[8] = list2.get(j).getDescription();
obj[9] = list2.get(j).getName();
index++;
dataList.add(obj);
}
} else {
obj = new Object[10];
obj[0] = index;
obj[1] = list.get(i).getCode();
obj[2] = list.get(i).getName();
obj[3] = list.get(i).getVersion();
obj[4] = list.get(i).getBponame();
obj[5] = list.get(i).getUpbponame();
obj[6] = DateUtil.formatDate(list.get(i).getCreateon()
.getTime(), "yyyy-MM-dd HH:mm:ss");
obj[7] = "";
obj[8] = "";
obj[9] = "";
index++;
dataList.add(obj);
}
}
}
ExportExcelUtil export = new ExportExcelUtil(title, rowName, dataList,
response);
export.exportData(title, rowName, dataList, response);
}