欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Spring Boot 前端通过请求接口下载后端存储的 Excel 模板

最编程 2024-07-03 15:53:35
...
package com.yutu.garden.utils; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import org.apache.commons.io.IOUtils; import org.apache.poi.hssf.util.HSSFColor; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.poi.hssf.usermodel.*; import org.apache.poi.ss.usermodel.*; import org.springframework.core.io.ResourceLoader; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * @ClassName: ExcelUtils * @Description: Excel相关操作 * @Author * @Date 2022/4/11 * @Version 1.0 */ @Component public class ExcelUtils { @Resource private ResourceLoader resourceLoader; private static Logger log = LoggerFactory.getLogger(ExcelUtils.class); static{ System.setProperty("java.awt.headless", "true"); } /** * 设置表头 * @param sheet sheet * @param str 表头数据 * @param startNum 开始行 * @param height 高度 * @param style 样式 */ public static void setTitle(HSSFSheet sheet, String[] str,int startNum,Short height,HSSFCellStyle style,Integer[] widths,int width) { try { HSSFRow row = sheet.createRow(startNum); if(ObjectUtils.isEmpty(height)){ height = (short)(20*20); } row.setHeight(height); //创建表头名称 HSSFCell cell; for (int j = 0; j < str.length; j++) { cell = row.createCell(j); //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度 if(ObjectUtils.isNotEmpty(widths) && ObjectUtils.isNotEmpty(widths[j]) ){ sheet.setColumnWidth(j, widths[j]); }else{ sheet.autoSizeColumn(j); int colWidth = sheet.getColumnWidth(j) * width / 10; // if (colWidth > 255) { // colWidth = 255; // } sheet.setColumnWidth(j, colWidth); } cell.setCellValue(str[j]); cell.setCellStyle(style); } } catch (Exception e) { e.printStackTrace(); } } public static void setTitle(HSSFSheet sheet, List<String> str,int startNum,Short height,HSSFCellStyle style,Integer[] widths) { try { HSSFRow row = sheet.createRow(startNum); if(ObjectUtils.isEmpty(height)){ height = (short)(20*20); } row.setHeight(height); //创建表头名称 HSSFCell cell; for (int j = 0; j < str.size(); j++) { cell = row.createCell(j); //设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度 if(ObjectUtils.isNotEmpty(widths) && ObjectUtils.isNotEmpty(widths[j]) ){ sheet.setColumnWidth(j, widths[j]); }else{ sheet.autoSizeColumn(j); sheet.setColumnWidth(j, sheet.getColumnWidth(j) * 30 / 10); } cell.setCellValue(str.get(j)); cell.setCellStyle(style); } } catch (Exception e) { e.printStackTrace(); } } /** * 方法名:setData * 功能:表格赋值 */ public static void setData(HSSFSheet sheet, List<Object[]> data,int startNum,HSSFCellStyle style) { try{ int rowNum = startNum+1; for (int i = 0; i < data.size(); i++) { HSSFRow row = sheet.createRow(rowNum); for (int j = 0; j < data.get(i).length; j++) { HSSFCell cell = row.createCell(j); if(ObjectUtils.isEmpty(data.get(i)[j])){ cell.setCellValue(""); }else{ cell.setCellValue(data.get(i)[j].toString()); } cell.setCellStyle(style); } rowNum++; } }catch (Exception e){ e.printStackTrace(); } } public static void setDataByList(HSSFSheet sheet, List<List<Object>> data,int startNum) { try{ int rowNum = startNum+1; for (int i = 0; i < data.size(); i++) { HSSFRow row = sheet.createRow(rowNum); for (int j = 0; j < data.get(i).size(); j++) { if(ObjectUtils.isEmpty(data.get(i).get(j))){ row.createCell(j).setCellValue(""); }else{ row.createCell(j).setCellValue(data.get(i).get(j).toString()); } } rowNum++; } }catch (Exception e){ e.printStackTrace(); } } /** * 方法名:setBrowser * 功能:使用浏览器下载 */ public static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) { try { //清空response //response.reset(); //设置response的Header String name = URLEncoder.encode(fileName, "UTF-8"); //Content-disposition 的 attachment参数将文件作为附件下载 //response.setHeader("Content-disposition", "attachment;filename=" + fileName+".xlsx"); response.setHeader( "Content-Disposition", "attachment;filename=\"" + name + "\".xlsx;filename*=utf-8''" + name +".xlsx"); OutputStream os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding("utf-8"); //将excel写入到输出流中 workbook.write(os); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 居中 * @param workbook * @return */ public static HSSFCellStyle getStyleByCENTER(HSSFWorkbook workbook,int size){ //设置标题样式 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBold(true); font.setFontName("宋体"); font.setFontHeightInPoints((short) size); style.setFont(font); //水平居中 style.setAlignment(HorizontalAlignment.CENTER); //垂直居中 style.setVerticalAlignment(VerticalAlignment.CENTER); style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); return style; } /** * 带边框的样式 * @param workbook workbook * @param size 字体大小 * @param isText 是否正文 * @return */ public static HSSFCellStyle getStyleByBorder(HSSFWorkbook workbook,int size,boolean isText){ //设置标题样式 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); if(!isText){ font.setBold(true); } font.setFontName("宋体"); font.setFontHeightInPoints((short) size); style.setFont(font); //水平居中 style.setAlignment(HorizontalAlignment.CENTER); //垂直居中 style.setVerticalAlignment(VerticalAlignment.CENTER); style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm")); //边框 style.setBorderBottom(BorderStyle.THIN); style.setBorderLeft(BorderStyle.THIN); style.setBorderTop(BorderStyle.THIN); style.setBorderRight(BorderStyle.THIN); return style; } public static HSSFCellStyle getDataStyle(HSSFWorkbook workbook,int size,boolean isSetBold,HSSFColor.HSSFColorPredefined background){ //设置标题样式 HSSFCellStyle style = workbook.createCellStyle(); HSSFFont font = workbook.createFont(); font.setBold(isSetBold); font.setFontName("宋体"); font.setFontHeightInPoints((short) size); style.setFont(font); if(ObjectUtils.isNotEmpty(background)){//设置填充方式 style.setFillPattern(FillPatternType.SOLID_FOREGROUND); style.setFillForegroundColor(background.getIndex()); } return style; } /** * 解析上传的excel, 默认只解析第一张Sheet * * @param file excel * @param startRow 数据开始行 * @return List<String [ ]> * @throws IOException */ public static List<String> getExcelData(MultipartFile file, int startRow, Integer endRow){ int resultSize = 0; ArrayList<String> resultData = new ArrayList<>(resultSize); try { if (!checkFile(file)) { log.error("上传的excel文件格式有问题"); return resultData; } //获得Workbook工作薄对象 Workbook workbook = getWorkBook(file); if (ObjectUtils.isNotEmpty(workbook)) { //获取第一张sheet工作表 Sheet sheet = workbook.getSheetAt(0); if (ObjectUtils.isEmpty(sheet)) { return resultData; } // 重新初始化List结果大小 resultSize = sheet.getLastRowNum() + 1; //获得当前sheet的开始行 int firstRowNum = sheet.getFirstRowNum(); //获得当前sheet的结束行 int lastRowNum = sheet.getLastRowNum(); if(ObjectUtils.isNotEmpty(endRow)){ lastRowNum = endRow; } //循环除了startRow的所有行,如果要循环除第一行以外的就firstRowNum+1 for (int rowNum = firstRowNum + startRow; rowNum <= lastRowNum; rowNum++) { //获得当前行 Row row = sheet.getRow(rowNum); if (rowIsEmpty(row)) { break; } //获得当前行的开始列 int firstCellNum = row.getFirstCellNum(); //获得当前行的列数 int lastCellNum = row.getLastCellNum(); //String[] cells = new String[lastCellNum]; StringBuilder stringBuffer = new StringBuilder(); //循环当前行 for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) { Cell cell = row.getCell(cellNum); //cells[cellNum] = getCellValue(cell); String cellValue = getCellValue(cell); stringBuffer.append(getCellValue(cell)).append(",&");//加个&防止有答案中有,的 } //resultData.add(cells); resultData.add(stringBuffer.toString()); } workbook.close(); } } catch (IOException e) { e.printStackTrace(); } return resultData; } /** * 检查文件格式 * * @param file * @throws IOException */ public static boolean checkFile(MultipartFile file) throws IOException

推荐阅读