java实现写入excel数据,或者前端导出excel都可以
首先处理excel表,制作一个模板(按照需求修改标题的属性值)
下面直接上java代码
1.依赖
<!-- 引入poi,解析workbook视图 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
2.下面是用例:
(1)普通写入excel
package com.example.demo.utils;
import com.example.demo.entity.CountAttendanceEntity;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author wangchang
* @Description TODO
* @createTime 2022年01月12日
*/
public class WriteExcel {
/**
* 写数据
*
* @param countAttendanceEntityList
* @param str1
* @param str2
* @throws IOException
*
*/
public void writeExcel(List<CountAttendanceEntity> countAttendanceEntityList, String str1, String str2) throws IOException {
Map<String, String> map = new HashMap<String, String>();
ClassPathResource resource = new ClassPathResource("/BOOT-INF/classes/countAttendance1.xlsx");
InputStream fis = resource.getInputStream();
SheetProcessor processor = (SheetProcessor) TemplateProcessorFactory.getSheetProcessorFromStream(fis);
processor.writeEntry(map);
for (CountAttendanceEntity entity : countAttendanceEntityList) {
Map<String, String> entry = new HashMap<String, String>();
entry.put("xh", entity.getXh());
entry.put("name", entity.getName());
entry.put("orgName", entity.getOrgName());
entry.put("startWorkTime", entity.getStartWorkTime());
entry.put("endWorkTime", entity.getEndWorkTime());
entry.put("workTime", entity.getWorkTime());
entry.put("addWorkTime", entity.getAddWorkTime());
entry.put("addWorkCS", entity.getAddWorkCS());
entry.put("noWorkTime", entity.getNoWorkTime());
entry.put("noWorkTS", entity.getNoWorkTS());
entry.put("totalWorkTime", entity.getTotalWorkTime());
entry.put("forgetDKCS", entity.getForgetDKCS());
entry.put("lateWorkCS", entity.getLateWorkCS());
processor.writeEntry(entry);
}
String filename = str1 + "年" + str2 + "月考勤表.xlsx";
OutputStream out = null;
try {
out = new FileOutputStream(filename);
processor.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
(2)导出exel
@GetMapping()
public void exportExcel(HttpServletRequest req, HttpServletResponse resp, PageExportParam pageExportParam) throws IOException, ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
PageParam pageInfo = new PageParam();
pageInfo.setPageSize(10000);
pageInfo.setPage(1);
pageInfo.setTime(sdf.parse(pageExportParam.getTime()));
pageInfo.setType(pageExportParam.getType());
List<Sort.Order> orders = new ArrayList<>();
orders.add(new Sort.Order(Sort.Direction.DESC, "checkinTime"));
orders.add(new Sort.Order(Sort.Direction.ASC, "userId"));
Sort sort = new Sort(orders);
PageRequest page = new PageRequest(pageInfo.getPage() - 1, pageInfo.getPageSize(), sort);
List<AttendanceDetail> resultList = new ArrayList<AttendanceDetail>();
if (pageInfo.getType().equals("选项1")) {
Page<AttendanceDetail> result = countAttendanceService.queryAllAttendance(page);
resultList = result.getContent();
} else if (pageInfo.getType().equals("选项3")) {
Paging<AttendanceDetail> list = countAttendanceService.queryByWeek(pageInfo);
resultList = list.getData();
} else {
Page<AttendanceDetail> list = countAttendanceService.queryByTime(page, pageInfo.getType(), pageInfo.getTime());
resultList = list.getContent();
}
Map<String, String> map = new HashMap<String, String>();
String date = sdf.format(pageInfo.getTime());
if (pageInfo.getType().equals("选项1")) {
date = "全部";
} else if (pageInfo.getType().equals("选项3")) {
date = getWeeks(date);
} else if (pageInfo.getType().equals("选项4")) {
date=date.substring(0,7);
}
map.put("titleName", "考勤数据" + date);
req.setCharacterEncoding("UTF-8");
String path = req.getServletContext().getRealPath("/WEB-INF/classes/attendance.xls");
FileInputStream ipst = new FileInputStream(path);
SheetProcessor processor = (SheetProcessor) TemplateProcessorFactory.getSheetProcessorFromStream(ipst);
processor.writeEntry(map);
for (AttendanceDetail entity : resultList) {
Map<String, String> entry = new HashMap<String, String>();
entry.put("userId", entity.getUserId());
entry.put("userName", entity.getUserName());
entry.put("groupName", entity.getGroupName());
entry.put("checkinType", entity.getCheckinType());
entry.put("exceptionType", entity.getExceptionType());
entry.put("checkinTime", entity.getCheckinTime());
entry.put("schCheckinTime", entity.getSchCheckinTime());
entry.put("locationTitle", entity.getLocationTitle());
entry.put("locationDetail", entity.getLocationDetail());
entry.put("wifiName", entity.getWifiName());
entry.put("notes", entity.getNotes());
processor.writeEntry(entry);
}
resp.setContentType("application/octet-stream");
resp.setHeader("Content-Disposition",
"attachment; filename=" + java.net.URLEncoder.encode("考勤数据" + "(" + date + ")" + ".xlsx", "UTF-8"));
processor.write(resp.getOutputStream());
}
3.工具类
package com.example.demo.utils;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
public interface SheetProcessor {
void writeEntry(Map<String, String> map);
void write(OutputStream out) throws IOException;
}
package com.example.demo.utils;
import org.apache.poi.hssf.util.AreaReference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;
public class SheetProcessorImpl implements SheetProcessor {
private Workbook workbook;
private int rowIdx = 0;
public SheetProcessorImpl(Workbook workbook) {
super();
this.workbook = workbook;
}
@Override
public void writeEntry(Map<String, String> map) {
for (Entry<String, String> entry : map.entrySet()) {
try {
AreaReference areaReference = new AreaReference(workbook.getName(entry.getKey()).getRefersToFormula());
CellReference cellRef = areaReference.getFirstCell();
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
if (rowIdx == 0) {
font.setFontName("宋体");
font.setFontHeightInPoints((short) 13);
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
}
font.setFontName("楷体_GB2312");
font.setFontHeightInPoints((short) 13);
cellStyle.setFont(font);
cellStyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
cellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
cellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
cellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
cellStyle.setAlignment(CellStyle.ALIGN_CENTER); // 居中
Sheet sheet = workbook.getSheet(cellRef.getSheetName());
Row row = sheet.getRow(cellRef.getRow() + rowIdx);
if (row == null) {
row = sheet.createRow(cellRef.getRow() + rowIdx);
}
Cell cell = row.createCell(cellRef.getCol());
cell.setCellStyle(cellStyle);
cell.setCellValue(entry.getValue());
} catch (NullPointerException e) {
}
}
rowIdx++;
}
@Override
public void write(OutputStream out) throws IOException {
workbook.write(out);
}
}
package com.example.demo.utils;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import java.io.IOException;
import java.io.InputStream;
public class TemplateProcessorFactory {
public static SheetProcessor getSheetProcessorFromStream(InputStream sheetInputStream) {
try {
return new SheetProcessorImpl(WorkbookFactory.create(sheetInputStream));
} catch (EncryptedDocumentException | InvalidFormatException | IOException e) {
throw new RuntimeException(e);
}
}
}
直接可以用的,用不了的可以滴滴我!!