Java export/import Excel by POI(Apache)

报表统计信息时常常有录入录出的功能。 一般为了省事直接用一些模板(freemarker的固定好ftl文件内容格式),然后直接插数据导出excel即可。

这里我用的是apache poi方式 对excel报表信息导入导出

导出excel

后台执行业务逻辑从库中查找到数据后,整合封装好后,输出到excel中去,最后用户下载即可

代码解释很详细了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package com.dottie.poi.controller;

import com.dottie.poi.entity.OccupationalEntity;
import com.dottie.poi.mapper.OccupationalMapper;
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.Row;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
* 导出报表
*/
public class ExportExcelController {

@Autowired
private OccupationalMapper occupationalMapper;


@GetMapping("/report")
public void reportExcel(HttpServletResponse resp) throws IOException {
// 创建一个excel
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建工作表
XSSFSheet sheet = workbook.createSheet();

// 设置标题和首行字体样式
Font font = workbook.createFont();
font.setFontName("黑体"); // 字体
font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 宽度
// 设置单元格类型
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 水平布局:居中
cellStyle.setWrapText(true);


// 创建标题行
Row row = sheet.createRow(0);
// 创建单元格
Cell cell = row.createCell((short) 0);
cell.setCellValue("登录商城用户分布统计");// 设置单元格内容
cell.setCellStyle(cellStyle);// 设置单元格样式
cell.setCellType(Cell.CELL_TYPE_STRING);// 指定单元格格式:数值、公式或字符串
// 合并单元格
sheet.addMergedRegion(new CellRangeAddress(0, // 第一行(0)
0, // last row(0-based)
0, // 第一列(基于0)
5 // 最后一列(基于0)
));


// 创建首行(字段说明行)
Row row1 = sheet.createRow(1);
String[] titles = {"字段1","字段2","字段3","字段4","字段5","字段6"};
for (int i = 0; i < titles.length; i++) {
// 创建单元格
Cell cell1 = row1.createCell((short) i);
cell1.setCellValue(titles[i]);// 设置单元格内容
cell1.setCellStyle(cellStyle);// 设置单元格样式
cell1.setCellType(Cell.CELL_TYPE_STRING);// 指定单元格格式:数值、公式或字符串
}


// 正文数据
List<OccupationalEntity> list = occupationalMapper.getAll();
for (int i = 0; i < list.size(); i++) {
OccupationalEntity entity = list.get(i);

Row row2 = sheet.createRow(i+2);

Cell row2Cell = row2.createCell((short) 0);
row2Cell.setCellValue(entity.getId());

Cell row3Cell = row2.createCell((short) 1);
row3Cell.setCellValue(entity.getType());

Cell row4Cell = row2.createCell((short) 2);
row4Cell.setCellValue(entity.getName());

Cell row5Cell = row2.createCell((short) 3);
row5Cell.setCellValue(entity.getId());

Cell row6Cell = row2.createCell((short) 4);
row6Cell.setCellValue(entity.getType());

Cell row7Cell = row2.createCell((short) 5);
row7Cell.setCellValue(entity.getName());
}
sheet.autoSizeColumn((short) 0); // 调整第一列宽度
sheet.autoSizeColumn((short) 1); // 调整第二列宽度
sheet.autoSizeColumn((short) 2); // 调整第三列宽度
sheet.autoSizeColumn((short) 3); // 调整第四列宽度
sheet.autoSizeColumn((short) 4); // 调整第四列宽度
sheet.autoSizeColumn((short) 5); // 调整第四列宽度

// 输出结果
String fileName = "账户数据.xlsx";
resp.setHeader("Content-disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"), "ISO8859-1")); //设置文件头编码格式
resp.setContentType("APPLICATION/OCTET-STREAM;charset=UTF-8");//设置类型
resp.setHeader("Cache-Control", "no-cache");//设置头

workbook.write(resp.getOutputStream());
resp.getOutputStream().flush();
resp.getOutputStream().close();
}

}

导入excel文件(解析excel)

这里这是做个测试,需要将该成你自己测试的excel文件所在路径。

导入excel获取对应数据,对其处理后入库等操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package com.dottie.poi.controller;

import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
* 导入excel对其解析
*/
public class ImportExcelController {

public static void main(String[] args) throws IOException, InvalidFormatException {
ImportExcelController();
}

public static void ImportExcelController() throws IOException, InvalidFormatException {
InputStream inputStream = new FileInputStream("/Users/daejong/Desktop/data.xlsx");

Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);

DataFormatter formatter = new DataFormatter();
for (Row row : sheet) {
for (Cell cell : row) {
CellReference cellRef = new CellReference(row.getRowNum(), cell.getColumnIndex());
//单元格名称
System.out.print(cellRef.formatAsString());
System.out.print(" - ");

//通过获取单元格值并应用任何数据格式(Date,0.00,1.23e9,$ 1.23等),获取单元格中显示的文本
String text = formatter.formatCellValue(cell);
System.out.println(text);

//获取值并自己格式化
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:// 字符串型
System.out.println(cell.getRichStringCellValue().getString());
break;
case Cell.CELL_TYPE_NUMERIC:// 数值型
if (DateUtil.isCellDateFormatted(cell)) { // 如果是date类型则 ,获取该cell的date值
System.out.println(cell.getDateCellValue());
} else {// 纯数字
System.out.println(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:// 布尔
System.out.println(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:// 公式型
System.out.println(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK:// 空值
System.out.println();
break;
case Cell.CELL_TYPE_ERROR: // 故障
System.out.println();
break;
default:
System.out.println();
}
}
}
}
}