pom依赖
也许不需要这么多依赖,自行筛包
<!-- excel 操作 -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-excelant</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.0.1</version>
</dependency>
导出
controller
/**
* 下载模板
* @param response
*/
@PostMapping("downloadTemplate")
public void downloadTemplate(HttpServletResponse response){
excelBatchAppendService.downloadTemplate(response);
}
service
/**
* 模板下载
* @param response
*/
@Override
public void downloadTemplate(HttpServletResponse response) {
String filename = "标准参数导入模板.xls";
String[] columnName = new String[]{"标准代码","问题概括","扣分规则","扣分单位","积分扣减"};
List<Object[]> dataList = new ArrayList<>();
Object[] objs;
// ⬇ 此区间代码 可以放入for循环中 将dao层查询的数据导出至excel中
objs = new Object[5];
objs[0] = "1-1" ;
objs[1] = "xxxx" ;
objs[2] = "yyyy" ;
objs[3] = "5" ;
objs[4] = "2" ;
dataList.add(objs);
// ⬆ 以上
ExportExcelUtil.export(filename,response,columnName,dataList);
}
导入
controller
/**
* excel数据批量导入
* @param file
* @param sap
* @param name
*/
@PostMapping("/batchAppend")
public void postBatchAppend(@RequestParam MultipartFile file,@RequestParam String sap,@RequestParam String name){
excelBatchAppendService.postBatchAppend(file,sap,name);
}
service
/**
* excel数据批量导入
* @param file
* @param sap
* @param name
*/
@Override
public void postBatchAppend(MultipartFile file, String sap, String name) {
if (!StringUtils.isEmpty(sap) && ! StringUtils.isEmpty(name)){
List<Map<Object,Object>> excelList = new ArrayList<>();
Workbook wb ;
Sheet sheet = null;
try{
//文件解析
wb = Workbook.getWorkbook(file.getInputStream());
sheet = wb.getSheet(0);
logger.info("文件初始化成功");
}catch (Exception e){
logger.error("文件初始化失败");
throw new BizException("文件初始化失败", ErrorCod.FAIL_TO_IMPORT);
}
if (null != sheet){
//初始行列(表头所在行列)
//初始行号,通常是0
int initRow = sheet.findLabelCell(SIGN).getRow();
//初始列号,通常是1
int initColumn = sheet.findLabelCell(SIGN).getColumn();
//总行数(包括表头上面可能存在的空行)
int totalRow = sheet.getRows();
logger.info("共" + ( totalRow - initRow - 1 ) + "条数据");
//装载每条数据的实体(数据库表的实体类,当前用map代替)
Map<Object,Object> itemMap;
for (int j = initRow + 1; j < totalRow; j++) {
itemMap = new HashMap<>();
//数据所在相对行数(实际上就是第几条数据,仅用来记录数据)
int dataRow = j - initRow;
logger.info("正在解析第"+ dataRow + "条数据......");
//得到该行所有单元格
Cell[] cells = sheet.getRow(j);
//只解析有数据的行
if (null != cells && cells.length>0){
for (int k = initColumn; k < cells.length; k++) {
//数据所在相对列数(实际上就是某条数据的第几列)
int dataColumn = k - initColumn + 1 ;
logger.info("正在解析第"+ dataRow + "条数据的第"+ dataColumn +"列......");
//读取当前单元格的值
String cellValue = cells[k].getContents().trim();
//校验并装在数据
if (dataColumn == 1){
if (StringUtils.isEmpty(cellValue)){
logger.error("第"+ dataRow +"条数据的标准代码不能为空");
throw new BizException("第"+ dataRow +"条数据的标准代码不能为空", ErrorCod.FAIL_TO_IMPORT);
}
itemMap.put("标准代码",cellValue);
}
if (dataColumn == 2){
if (StringUtils.isEmpty(cellValue)){
logger.error("第"+ dataRow +"条数据的问题概括不能为空");
throw new BizException("第"+ dataRow +"条数据的问题概括不能为空", ErrorCod.FAIL_TO_IMPORT);
}
itemMap.put("问题概括",cellValue);
}
if (dataColumn == 3){
if (StringUtils.isEmpty(cellValue)){
logger.error("第"+ dataRow +"条数据的扣分规则不能为空");
throw new BizException("第"+ dataRow +"条数据的扣分规则不能为空", ErrorCod.FAIL_TO_IMPORT);
}
itemMap.put("扣分规则",cellValue);
}
if (dataColumn == 4){
if (StringUtils.isEmpty(cellValue.replaceAll(" ",""))){
logger.error("第"+ dataRow +"条数据的标准扣分单位不能为空");
throw new BizException("第"+ dataRow +"条数据的标准扣分单位不能为空", ErrorCod.FAIL_TO_IMPORT);
}
try {
itemMap.put("标准扣分单位", BigDecimal.valueOf(Double.parseDouble(cellValue.replaceAll(" ",""))));
}catch (NumberFormatException e){
logger.error("第"+ dataRow +"条数据的标准扣分单位书写格式错误");
throw new BizException("第"+ dataRow +"条数据的标准扣分单位书写格式错误", ErrorCod.FAIL_TO_IMPORT);
}
}
if (dataColumn == 5){
if (StringUtils.isEmpty(cellValue.replaceAll(" ",""))){
logger.error("第"+ dataRow +"条数据的个人积分扣减不能为空");
throw new BizException("第"+ dataRow +"条数据的个人积分扣减不能为空", ErrorCod.FAIL_TO_IMPORT);
}
try {
itemMap.put("个人积分扣减", BigDecimal.valueOf(Double.parseDouble(cellValue.replaceAll(" ",""))));
}catch (NumberFormatException e){
logger.error("第"+ dataRow +"条数据的个人积分扣减书写格式错误");
throw new BizException("第"+ dataRow +"条数据的个人积分扣减书写格式错误", ErrorCod.FAIL_TO_IMPORT);
}
}
}
//将维护人信息也记录在实体中
itemMap.put("sap",sap);
itemMap.put("name",name);
}
excelList.add(itemMap);
}
//后续 数据处理.....
System.out.println(excelList);
}
}else {
logger.error("参数错误");
throw new BizException("参数错误", ErrorCod.FAIL_TO_IMPORT);
}
}
工具类
导出
/**
* excel导出工具类
*/
public class ExportExcelUtil {
public static void export(String filNam, HttpServletResponse response, String[] columnName, List<Object[]> dataList) {
try {
//创建工作簿对象
HSSFWorkbook workbook = new HSSFWorkbook();
//创建工作表
HSSFSheet sheet = workbook.createSheet("sheet名");
//sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法】
//获取列头样式对象
HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook);
//单元格样式对象
HSSFCellStyle style = getStyle(workbook);
//定义所需列数
int columnNum = columnName.length;
//在索引2的位置创建行(最顶端的行开始第二行)
HSSFRow rowRowNam = sheet.createRow(0);
//设置高度
rowRowNam.setHeight((short) (25 * 25));
//将列头设置到sheet的单元格中
for (int n = 0; n < columnName.length; n++) {
//创建列头对应个数的单元格
HSSFCell cellRowNam = rowRowNam.createCell(n);
//设置列头单元格的数据类型
cellRowNam.setCellType(CellType.STRING);
HSSFRichTextString text = new HSSFRichTextString(columnName[n]);
//设置列头单元格的值
cellRowNam.setCellValue(text);
//设置列头单元格样式
cellRowNam.setCellStyle(columnTopStyle);
}
//将查询出的数据设置到sheet对应的单元格中
for (int i = 0; i < dataList.size(); i++) {
//遍历每个对象
Object[] obj = dataList.get(i);
//创建所需的行数
HSSFRow row = sheet.createRow(i + 1);
//设置高度
row.setHeight((short) (25 * 20));
for (int j = 0; j < obj.length; j++) {
//设置单元格的数据类型
HSSFCell cell;
cell = row.createCell(j, CellType.STRING);
if (null != obj[j]) {
//设置单元格的值
cell.setCellValue(obj[j].toString());
} else {
//设置单元格的值
cell.setCellValue("(null)");
}
//设置单元格样式
cell.setCellStyle(style);
}
}
//让列宽随着导出的列长自动适应
for (int colNum = 0; colNum < columnNum; colNum++) {
int columnWidth = sheet.getColumnWidth(colNum)/256 ;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//当前行未被使用过
if (sheet.getRow(rowNum) == null){
currentRow = sheet.createRow(rowNum);
}else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(colNum) != null){
HSSFCell currentCell = currentRow.getCell(colNum);
if (currentCell.getCellType() == CellType.STRING){
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length){
columnWidth = length;
}
}
}
}
//sheet.setColumnWidth(colNum,(columnWidth + 4) * 256);
//首次优化
//sheet.setColumnWidth(colNum,(columnWidth + 4) * 256 > 65280 ? 65280 : (columnWidth + 4) * 256);
//二次优化
if (columnWidth <255){
sheet.setColumnWidth(colNum,(columnWidth + 4) * 256);
}else {
sheet.setColumnWidth(columnNum,6000);
}
}
try {
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setCharacterEncoding("UTF-8");
response.addHeader("Content-Disposition","attachment;filename="+new String(filNam.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1));
OutputStream out = response.getOutputStream();
workbook.write(out);
out.close();
}catch (IOException e){
e.printStackTrace();
}
}catch (Exception e){
e.printStackTrace();
}
}
public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
//设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short) 11);
//字体加粗
font.setBold(true);
//设置字体名字
//font.setFontName("Arial");
//设置样式
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色
style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置左边框
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色
style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置右边框
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色
style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置顶边框
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色
style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//在样式用应用设置的字体
style.setFont(font);
//设置自动换行
style.setWrapText(false);
//设置水平对齐的样式为居中对齐
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
public static HSSFCellStyle getStyle(HSSFWorkbook workbook) {
//设置字体
HSSFFont font = workbook.createFont();
//设置字体大小
//font.setFontHeightInPoints((short) 10);
//字体加粗
//font.setBold(true);
//设置字体名字
//font.setFontName("Courier New");
//设置样式
HSSFCellStyle style = workbook.createCellStyle();
//设置底边框
style.setBorderBottom(BorderStyle.THIN);
//设置底边框颜色
style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置左边框
style.setBorderLeft(BorderStyle.THIN);
//设置左边框颜色
style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置右边框
style.setBorderRight(BorderStyle.THIN);
//设置右边框颜色
style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//设置顶边框
style.setBorderTop(BorderStyle.THIN);
//设置顶边框颜色
style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
//在样式用应用设置的字体
style.setFont(font);
//设置自动换行
style.setWrapText(false);
//设置水平对齐的样式为居中对齐
style.setAlignment(HorizontalAlignment.CENTER);
//设置垂直对齐的样式为居中对齐
style.setVerticalAlignment(VerticalAlignment.CENTER);
return style;
}
}