POI的导入导出Excel(复制粘贴即可使用!)
程序员文章站
2022-07-14 17:22:09
...
控制层:
导出:主要是接收页面的条件,然后根据条件去数据库查需要导出的数据
导入:接收文件,调用服务
/*
* 导出
* 按照页面的条件导出
*/
@RequestMapping(params = "exportExcel")
@ResponseBody
public void exportExcel(HttpServletRequest request,HttpServletResponse response) {
//接收条件
String xm = request.getParameter("xm");
String sfzmhm = request.getParameter("sfzmhm");
String kscx = request.getParameter("kscx");
String startTime = request.getParameter("startTime") == null ? "" : request.getParameter("startTime");
String endTime = request.getParameter("endTime") == null ? "" : request.getParameter("endTime");
List<HhStudent> list = studentService.queryAllStudentInfo(xm,sfzmhm,kscx,startTime,endTime);
studentService.export(list,startTime,endTime,request,response);
}
/*
* 导入考生
*/
@RequestMapping(params = "importExcel", method=RequestMethod.POST, produces = "text/html;charset=utf-8")
@ResponseBody
public String getPathfileName(@RequestParam("file")MultipartFile file) {
String msg = studentService.saveStudent(file);
return msg;
}
服务层(模板......):
导出:不同业务,不同格式,在这里面设置就行了
导入:直接调用List <List <String >> list = POIUtil.readExcel(file,3);
返回格式如下:
假如 数据库表:student
xm age
张三 18
李四 20
王五 50
那么List<List<String>> list = POIUtil.readExcel(file, 3);
返回的数据就是
[[张三,18],[李四,20],[王五,50]]
//导出
public void export(List<HhStudent> list, String startTime, String endTime,HttpServletRequest request,HttpServletResponse response) {
//导出文件的名字
String fileName = "考生信息.xlsx";
//第一行内容
List<Map<String, Object>> titleList = new ArrayList<>();
Map<String, Object> titlemap1 = new HashMap<>();
titlemap1.put("tableName", "考生信息表");
titlemap1.put("fontHeight", 18);
titlemap1.put("fontName", "宋体");
titlemap1.put("alignment", XSSFCellStyle.ALIGN_CENTER);
titleList.add(titlemap1);
//第二行内容
String requestdate = startTime+" 至"+endTime;
Map<String, Object> titlemap2 = new HashMap<String, Object>();
String time = requestdate.equals("") ? "全部时间" : requestdate;
titlemap2.put("tableName", "起止时间:" + time + " 打印时间:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
titlemap2.put("fontHeight", 10);
titlemap2.put("fontName", "宋体");
titlemap2.put("alignment", XSSFCellStyle.ALIGN_CENTER);
titleList.add(titlemap2);
//一共有4列
int lieNum = 4;
//设置所需要导出的list集合的开始行索引-----也就是从第4行开始录入信息:结果如最后的附图
int startIndex = 3;
//列名称
List<String> columnList = new ArrayList<String>();
columnList.add("姓名");
columnList.add("身份证号码");
columnList.add("约考日期");
columnList.add("考试车型");
//列格式
Map<String, Object> columnStyleMap = new HashMap<String, Object>();
columnStyleMap.put("frontHight", 10);
columnStyleMap.put("frontName", "宋体");
columnStyleMap.put("isJiaCu", true);
/*
* 返回map中包括
* XSSFWorkbook book
* XSSFSheet sheet
* OutputStream out
*/
Map<String, Object> map = POIUtil.exportXls(request, response, fileName, startIndex, lieNum, titleList, columnList, columnStyleMap);
XSSFWorkbook book = (XSSFWorkbook)map.get("XSSFWorkbook");
XSSFSheet sheet = (XSSFSheet)map.get("XSSFSheet");
OutputStream out = (OutputStream)map.get("out");
//将list中的每个对象的内容写入到每一行
XSSFCellStyle style = book.createCellStyle();
style.setAlignment((short)XSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment((short)XSSFCellStyle.VERTICAL_CENTER);
int rowIndex=startIndex;
XSSFRow row = null;
XSSFCell cell = null;
for (HhStudent hhStudent : list) {
row = sheet.createRow(rowIndex);
cell = row.createCell(0);
cell.setCellValue(hhStudent.getXm());
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue(hhStudent.getSfzmhm());
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue(DateUtil.parTime(hhStudent.getYkrq()));
cell.setCellStyle(style);
cell = row.createCell(3);
cell.setCellValue(hhStudent.getKscx());
cell.setCellStyle(style);
rowIndex++;
}
try {
book.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 导入
*/
@Transactional
public String saveStudent(MultipartFile file) {
String msg=null;
Map<String, String> map3 = new HashMap<String, String>();
try {
//3:excel中第三行数据开始导入数据库
List<List<String>> list = POIUtil.readExcel(file, 3);
//批量添加的list
List<HhStudent> insertList = new ArrayList<HhStudent>();
//批量修改的list
List<HhStudent> updateList = new ArrayList<HhStudent>();
for(int i =0;i<list.size();i++) {
if(list.get(i).size()>0) {
if(!list.get(i).get(0).equals("总计")){
HhStudent student = new HhStudent();
student.setId(UUID.randomUUID().toString());
student.setXm(list.get(i).get(0));
student.setSfzmhm(list.get(i).get(1));
student.setYkrq(DateUtil.parse(list.get(i).get(2)));
student.setKscx(list.get(i).get(3));
if(!student.getXm().equals("")) {
HhStudentExample example = new HhStudentExample();
Criteria criteria = example.createCriteria();
criteria.andXmEqualTo(student.getXm());
criteria.andSfzmhmEqualTo(student.getSfzmhm());
criteria.andYkrqEqualTo(DateUtil.parse(list.get(i).get(2)));
List<HhStudent> example2 = hHstudentMapper.selectByExample(example);
if(example2.size()==0) {//无重复
insertList.add(student);
if(insertList.size()>=10){
hHstudentMapper.insertStudent(insertList);
insertList.clear();
}
}else {
student.setId(example2.get(0).getId());
updateList.add(student);
if(updateList.size()>=10){
hHstudentMapper.updateStudent(updateList);
updateList.clear();
}
}
}
}
}
}
if(insertList.size()>0) {
hHstudentMapper.insertStudent(insertList);
}
if(updateList.size()>0) {
hHstudentMapper.updateStudent(updateList);
}
map3.put("code", "200");
map3.put("msg", "保存成功!");
} catch (Exception e) {
map3.put("code", "201");
map3.put("msg", "保存失败!");
}
msg= JSON.toJSONString(map3);
return msg;
}
POIUtil:
public class POIUtil {
private static Logger logger = Logger.getLogger(POIUtil.class);
private final static String xls = "xls";
private final static String xlsx = "xlsx";
/**
* 读入excel文件,解析后返回
* @param file
* @throws IOException
*/
public static List<List<String>> readExcel(MultipartFile file,int startReadRow) throws IOException{
//检查文件
checkFile(file);
//获得Workbook工作薄对象
Workbook workbook = getWorkBook(file);
//创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
List<List<String>> list = new ArrayList< List<String>>();
//共有多少页
int sheetTotal = workbook.getNumberOfSheets();
if(workbook != null){
for(int sheetIndex = 0;sheetIndex < sheetTotal;sheetIndex++){
Sheet sheet = workbook.getSheetAt(sheetIndex);
//如果当前sheet为null,跳过
if(sheet == null){
continue;
}
//获得当前sheet的开始行索引,从0开始
int firstRowNum = sheet.getFirstRowNum();
//获得当前sheet的结束行索引
int lastRowNum = sheet.getLastRowNum();
for(int rowNum = firstRowNum+startReadRow-1;rowNum <= lastRowNum;rowNum++){
Row row = sheet.getRow(rowNum);
boolean b = isRowEmpty(row);
if (b) {
continue;
}
if(row == null){
continue;
}
//获得当前行的列数
int lastCellNum = row.getPhysicalNumberOfCells();
//创建一个cellList集合,用来存放当前
List<String> cellList = new ArrayList<>();
for (int i = 0; i < row.getPhysicalNumberOfCells(); i++) {
cellList.add(getCellValue(row.getCell(i)));
}
list.add(cellList);
}
}
}
//最终返回的是一个String类型的list数组
return list;
}
public static void checkFile(MultipartFile file) throws IOException{
//判断文件是否存在
if(null == file){
//该日志生成位置可以在log4j里面配置
logger.error("文件不存在!");
throw new FileNotFoundException("文件不存在!");
}
//获得文件名
String fileName = file.getOriginalFilename();
//判断文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
logger.error(fileName + "不是excel文件");
throw new IOException(fileName + "不是excel文件");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//获得文件名
String fileName = file.getOriginalFilename();
//创建Workbook工作薄对象,表示整个excel
Workbook workbook = null;
try {
//获取excel文件的io流
InputStream is = file.getInputStream();
//根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007 及2007以上
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
logger.info(e.getMessage());
}
return workbook;
}
public static String getCellValue(Cell cell){
//将空的单元格设置为"";
String cellValue = "";
if(cell == null){
return cellValue;
}
//把数字当成String来读,避免出现1读成1.0的情况
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判断数据的类型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //数字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知类型";
break;
}
return cellValue;
}
//判断某一行是不是为空行
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
return true;
}
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////
/*
* 导出excel
* fileName是带扩展名的全称
*/
public static Map<String, Object> exportXls(HttpServletRequest request,HttpServletResponse response,
String fileName,int startIndex ,int lieNum,List<Map<String, Object>> titleList,List<String> columnList,
Map<String, Object> columnStyleMap) {
OutputStream out = null;
Map<String, Object> map = new HashMap<String, Object>();
try {
out = response.getOutputStream();
//先拿到路径
String agent = request.getHeader("User-Agent");
fileName = FileUtils.encodeDownloadFilename(fileName, agent);
response.setHeader("content-disposition", "attachment;filename="+fileName);
XSSFWorkbook book = new XSSFWorkbook(); //新的工作薄
XSSFSheet sheet = book.createSheet("sheet1");
//设置列宽度
sheet.setColumnWidth(0, 4500);
sheet.setColumnWidth(1, 8000);
sheet.setColumnWidth(2, 8000);
sheet.setColumnWidth(3, 10000);
//设置开头几列文字
for (int i = 0; i < titleList.size(); i++) {
XSSFRow row = sheet.createRow(i);
XSSFCell cell = row.createCell(0);
// 设置单元格内容
cell.setCellValue(titleList.get(i).get("tableName").toString());
// 合并单元格CellRangeAddress构造参数依次表示起始行,截至行,起始列, 截至列
sheet.addMergedRegion(new CellRangeAddress(i, i, 0, lieNum-1));
XSSFCellStyle borderStyle = book.createCellStyle();
Font ztFont = book.createFont();
if (titleList.get(i).get("fontHeight") != null) {
int fontHeight = Integer.valueOf(titleList.get(i).get("fontHeight").toString());
ztFont.setFontHeightInPoints((short) fontHeight);
}
ztFont.setFontName(titleList.get(i).get("fontName").toString()); // 将“新宋体”字体应用到当前单元格上
if (titleList.get(i).get("fontBoldweight") != null) {
int fontBoldweight = Integer.valueOf(titleList.get(i).get("fontBoldweight").toString());
ztFont.setBoldweight((short) fontBoldweight);
}
borderStyle.setFont(ztFont);
if (titleList.get(i).get("alignment") != null) {
int alignment = Integer.valueOf(titleList.get(i).get("alignment").toString());
borderStyle.setAlignment((short) alignment);
}
cell.setCellStyle(borderStyle);
}
// 1.生成字体对象
XSSFFont font = book.createFont();
int fontHight = Integer.valueOf(columnStyleMap.get("frontHight").toString());
font.setFontHeightInPoints((short)fontHight);
font.setFontName((String)columnStyleMap.get("frontName"));
//判断是否需要加粗
if (columnStyleMap.get("isJiaCu")!=null && !columnStyleMap.get("isJiaCu").equals("")) {
font.setBold(true);
}
// 2.生成样式对象
XSSFCellStyle style = book.createCellStyle();
style.setAlignment((short)XSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment((short)XSSFCellStyle.VERTICAL_CENTER);
// 设置边框
// style.setBorderTop(BorderStyle.THIN);
// style.setBorderBottom(BorderStyle.THIN);
// style.setBorderLeft(BorderStyle.THIN);
// style.setBorderRight(BorderStyle.THIN);
style.setFont(font); // 调用字体样式对象
//是否长文本自动换行
style.setWrapText(true);
int rowIndex=startIndex;
XSSFRow row = null;
XSSFCell cell = null;
//设置每一列对应名称
for (int i = 0; i < columnList.size(); i++) {
row = sheet.createRow(startIndex-1);
cell = row.createCell(i);
cell.setCellValue(columnList.get(0));
cell.setCellStyle(style);
i++;
cell = row.createCell(i);
cell.setCellValue(columnList.get(1));
cell.setCellStyle(style);
i++;
cell = row.createCell(2);
cell.setCellValue(columnList.get(2));
cell.setCellStyle(style);
i++;
cell = row.createCell(3);
cell.setCellValue(columnList.get(3));
cell.setCellStyle(style);
}
map.put("XSSFSheet", sheet);
map.put("XSSFWorkbook", book);
map.put("rowIndex", rowIndex);
map.put("out", out);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
这样就很清楚了吧。
导出的图如下:
导入用到的的Excel:
推荐阅读
-
java使用POI批量导入excel数据的方法
-
使用PHP_XLSXWriter代替PHPExcel 实现excel数据的导入导出
-
java使用POI实现excel文件的导入和导出(通用方法)
-
Laravel 5使用Laravel Excel实现Excel/CSV文件导入导出的功能详解
-
POI的导入导出Excel(复制粘贴即可使用!)
-
Java POI 导入导出 Excel 的方式和区别
-
导出大数据量excel文件——poi的SXSSFWorkbook对象使用
-
使用POI实现Excel的导出功能
-
通过自定义注解+反射的形式,使用POI实现excel的导入导出
-
poi的入门使用,实现excel样式自定义导出,复制即可导出