目前对数据库记录导出Excel文件以及Excel文件的导入都可以调用POI的依赖实现,当然它是针对微软办公软件的文档格式读写的,想学习更多可以详细查一下GitHub上这个poi的源码。
<!--提供Microsoft Office格式文档读写-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.2</version>
</dependency>
多余的大家自己去网络查找或者去官方文档看吧,这里我详细分享这次我的项目用到它的点,以及怎么合理的实现通过网址的访问下载到这个Excel数据库文件。
这里处理List<T>类型的数据,我们可以根据T的实体类型进行表格的制定。
这里我采用的T是Attendance这个实体:
@EqualsAndHashCode(callSuper = true)
@Data
@TableName("attendance")
public class Attendance extends Model<Attendance> implements Serializable {
@TableId
private int Id;
private int floorSno;
private int dormitorySno;
private int bedSno;
private String clazz;
private String studentName;
private String Info;
}
总共七个属性也就是表格需要7列。
1、将List<Attendance>的数据转换到表格对象中并将表格文件写入HTTPServletResponse响应对象的输出流中。
import com.hlc.entity.Attendance;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.CellType;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
/**
* 操作Excel文件的工具类
*/
public class ExcelUtils {
/**
* 将数据库的某一表格数据导出为Excel文件并通过请求的响应体下载到电脑上。
*
* @param response HTTP响应对象
* @param data 数据库查询某一全表的数据
* @param sheetName 表格名
* @param columnWidth 表格列宽
*/
public static void putExcel(HttpServletResponse response, List<Attendance> data
, String sheetName, int columnWidth) {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);
sheet.setDefaultColumnWidth(columnWidth);
int rowIndex = 0;
int cellIndex = 0;
while (cellIndex < 7) {
HSSFRow row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++, CellType.STRING).setCellValue("宿舍楼号");
row.createCell(cellIndex++, CellType.STRING).setCellValue("宿舍号");
row.createCell(cellIndex++, CellType.STRING).setCellValue("床位号");
row.createCell(cellIndex++, CellType.STRING).setCellValue("班级");
row.createCell(cellIndex++, CellType.STRING).setCellValue("学生姓名");
row.createCell(cellIndex++, CellType.STRING).setCellValue("考勤信息");
row.createCell(cellIndex++, CellType.STRING).setCellValue("记录日期");
}
cellIndex = 0;
for (Attendance attendance : data) {
while (cellIndex < 7) {
HSSFRow row = sheet.createRow(rowIndex++);
row.createCell(cellIndex++, CellType.NUMERIC).setCellValue(attendance.getFloorSno());
row.createCell(cellIndex++, CellType.NUMERIC).setCellValue(attendance.getDormitorySno());
row.createCell(cellIndex++, CellType.NUMERIC).setCellValue(attendance.getBedSno());
row.createCell(cellIndex++, CellType.STRING).setCellValue(attendance.getClazz());
row.createCell(cellIndex++, CellType.STRING).setCellValue(attendance.getStudentName());
row.createCell(cellIndex++, CellType.STRING).setCellValue(attendance.getInfo());
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
HSSFCell cell = row.createCell(cellIndex++);
cell.setCellStyle(cellStyle);
cell.setCellValue(new Date());
}
cellIndex = 0;
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=student.xls");
response.flushBuffer();
workbook.write(response.getOutputStream());
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
逻辑不难看懂,主要需要注意的response的某些属性的配置,不明白的需要去查查了解一下。
2、在controller配置路由实现访问下载
@RestController
@RequestMapping("Attendance")
public class AttendanceController {
@Autowired
private AttendanceService attendanceService;
@Autowired
private UserMapper userMapper;
/**
* 将考勤信息表导出成Excel文件
*
* @param response 请求响应对象
*/
@GetMapping("/putExcel")
public void putExcel(HttpServletResponse response) {
try {
List<Attendance> attendanceList = attendanceService.query().list();
String sheetName = "学生考勤表";
ExcelUtils.putExcel(response, attendanceList, sheetName, 15);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取全部考勤记录信息
*
* @return 通用响应返回对象
*/
@GetMapping("/all")
@ResponseBody
public R<List<Attendance>> getAll() {
try {
List<Attendance> attendanceList = attendanceService.query().list();
R<List<Attendance>> r = new R<>();
r.setCode(1);
r.setData(attendanceList);
return r;
} catch (Exception e) {
e.printStackTrace();
return R.error("获取全部考勤记录失败!");
}
}
/**
* 提交新的考勤记录
*
* @param attendance 考勤记录实体对象
* @param wechatId 微信小程序openId用于验证身份
* @return 通用返回对象
*/
@PostMapping("/add")
@ResponseBody
public R<Boolean> addNew(@RequestParam("Attendance") Attendance attendance, @RequestParam("wechatId") String wechatId) {
try {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("WeChatId", wechatId);
boolean exists = userMapper.exists(wrapper);
if (exists) {
boolean save = attendanceService.save(attendance);
if (save) return R.success(true);
else return R.error("提交失败!");
} else return R.error("身份验证异常!");
} catch (Exception e) {
e.printStackTrace();
return R.error("提交失败!");
}
}
}
基本就是这些了,CV然后改改就可以套入你的项目使用,完全没得问题。
关于将Excel导入数据库的方法,大家可以看看我的这篇文章: