Apache POI是基于Office Open XML标准(OOXML)和Microsoft的OLE 2复合文档格式(OLE2)处理各种文件格式的开源项目。简单来说就是它可以通过Java程序读写Excel。
HSSF - 提供读写Microsoft Excel XLS格式(Microsoft Excel 97 (-2003))档案的功能。
XSSF - 提供读写Microsoft Excel OOXML XLSX格式(Microsoft Excel XML (2007+))档案的功能。
SXSSF - 提供低内存占用量读写Microsoft Excel OOXML XLSX格式档案的功能。
HWPF - 提供读写Microsoft Word DOC97格式(Microsoft Word 97 (-2003))档案的功能。
XWPF - 提供读写Microsoft Word DOC2003格式(WordprocessingML (2007+))档案的功能。
HSLF/XSLF - 提供读写Microsoft PowerPoint格式档案的功能。
HDGF/XDGF - 提供读Microsoft Visio格式档案的功能。
HPBF - 提供读Microsoft Publisher格式档案的功能。
HSMF - 提供读Microsoft Outlook格式档案的功能。
(本篇demo技术架构:SpringBoot + Swagger + MyBatis-Plus)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.0.0</version>
</dependency>
create table boot_user
(
user_id int auto_increment comment '用户ID' primary key,
user_name varchar(32) null comment '用户名',
user_sex int default 0 null comment '性别(0:男,1:女)',
user_age int null comment '年龄',
user_password varchar(32) null comment '密码',
user_status int default 0 null comment '状态(0:启用,1禁用)'
)
comment '用户表';
/**
* 导出工具类
* @Author: CTW
* @Date: create in 2021/7/24
*/
public class ExportUtils {
public static void ExportBootUser(HttpServletResponse response, String sheetName, String[] title, List<BootUser> bootUserList) {
//新建文档实例
XSSFWorkbook workbook = new XSSFWorkbook();
//在文档中添加表单
XSSFSheet sheet = workbook.createSheet(sheetName);
//创建单元格格式,并设置居中
XSSFCellStyle style = workbook.createCellStyle();
XSSFCellStyle style2 = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style2.setAlignment(HorizontalAlignment.CENTER);
//标题边框
//下边框
style.setBorderBottom(BorderStyle.THICK);
//左边框
style.setBorderLeft(BorderStyle.THICK);
//右边框
style.setBorderRight(BorderStyle.THICK);
//上边框
style.setBorderTop(BorderStyle.THICK);
//普通边框
//下边框
style2.setBorderBottom(BorderStyle.THIN);
//左边框
style2.setBorderLeft(BorderStyle.THIN);
//右边框
style2.setBorderRight(BorderStyle.THIN);
//上边框
style2.setBorderTop(BorderStyle.THIN);
//标题字体
XSSFFont font = workbook.createFont();
font.setFontName("仿宋_GB2312");
font.setBold(true);
font.setFontHeightInPoints((short) 14);
font.setColor(Font.COLOR_RED);
style.setFont(font);
//创建第一行,用于填充标题
XSSFRow titleRow = sheet.createRow(0);
//填充表头标题
for (int i = 0; i < title.length; i++) {
sheet.setColumnWidth(i, 18 * 256);
//创建单元格
XSSFCell cell = titleRow.createCell(i);
//设置单元格内容
cell.setCellValue(title[i]);
//设置单元格样式
cell.setCellStyle(style);
}
//填充内容
//行号
int i = 1;
XSSFRow row;
for (BootUser bootUser : bootUserList) {
//创建行
row = sheet.createRow(i);
//创建单元格
XSSFCell cell0 = row.createCell(0);
//设置单元格内容
cell0.setCellValue(bootUser.getUserName());
//设置单元格样式
cell0.setCellStyle(style2);
//创建单元格
XSSFCell cell1 = row.createCell(1);
//设置单元格内容
cell1.setCellValue(bootUser.getUserSex() == 0 ? "男" : "女");
//设置单元格样式
cell1.setCellStyle(style2);
//创建单元格
XSSFCell cell2 = row.createCell(2);
//设置单元格内容
cell2.setCellValue(bootUser.getUserAge());
//设置单元格样式
cell2.setCellStyle(style2);
//创建单元格
XSSFCell cell3 = row.createCell(3);
//设置单元格内容
cell3.setCellValue(bootUser.getUserPassword());
//设置单元格样式
cell3.setCellStyle(style2);
//创建单元格
XSSFCell cell4 = row.createCell(4);
//设置单元格内容
cell4.setCellValue(bootUser.getUserStatus() == 0 ? "启用" : "禁用");
//设置单元格样式
cell4.setCellStyle(style2);
i++;
}
//声明输出流
OutputStream outputStream = null;
//响应到客户端
try {
//表格文件名称
String fileName = sheetName + ".xlsx";
//设置响应头
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//获取输出流
outputStream = response.getOutputStream();
//用文档写输出流
workbook.write(outputStream);
//刷新输出流
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭输出流
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 导入工具类
* @Author: CTW
* @Date: create in 2021/7/24
*/
public class ImportUtils {
public static void ImportBootUser(MultipartFile file, BootUserService bootUserService) {
XSSFWorkbook workBook = null;
try (InputStream inputStream = file.getInputStream()) {
//读取文件流
workBook = new XSSFWorkbook(inputStream);
//读取工作表
XSSFSheet sheet = workBook.getSheetAt(0);
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
//读取行
XSSFRow row = sheet.getRow(i);
//读取单元格
XSSFCell cell0 = row.getCell(0);
XSSFCell cell1 = row.getCell(1);
XSSFCell cell2 = row.getCell(2);
XSSFCell cell3 = row.getCell(3);
XSSFCell cell4 = row.getCell(4);
//设置单元格类型
cell2.setCellType(CellType.STRING);
cell3.setCellType(CellType.STRING);
BootUser bootUser = new BootUser();
bootUser.setUserName(cell0.getStringCellValue());
bootUser.setUserSex("男".equals(cell1.getStringCellValue().trim()) ? 0 : 1);
bootUser.setUserAge((int) Float.parseFloat(cell2.getStringCellValue()));
bootUser.setUserPassword(cell3.getStringCellValue());
bootUser.setUserStatus("启用".equals(cell4.getStringCellValue().trim()) ? 0 : 1);
//保存用户数据
bootUserService.save(bootUser);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (workBook != null) {
try {
workBook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@Api(tags = "用户接口")
@RestController
@RequestMapping("/boot-user")
public class BootUserController {
@Resource
private BootUserService bootUserService;
@ApiOperation("查询全部用户")
@GetMapping("bootUserList")
public R<List<BootUser>> bootUserList() {
return R.ok(bootUserService.list());
}
@ApiOperation("导出用户数据")
@GetMapping("exportBootUser")
public void exportBootUser(HttpServletResponse response) {
String sheetName = "用户数据";
String[] title = {"用户名", "性别", "年龄", "密码", "状态"};
List<BootUser> bootUserList = bootUserService.list();
ExportUtils.ExportBootUser(response, sheetName, title, bootUserList);
}
@ApiOperation("导入用户数据")
@PostMapping("importBootUser")
public void importBootUser(@RequestParam("file") MultipartFile file) {
ImportUtils.ImportBootUser(file, bootUserService);
}
}