単一または複数のシートを生成でき、セルにリンクを含めることができます

最終効果

点击链接也可以进入对应的sheet中

ここに画像の説明を挿入します

1. POIエクスポートツールクラス

package org.springblade.common.utils.excel.util;

import java.io.Serializable;
import java.util.List;

/**
 * @program: BladeX
 * @description:
 * @author: lxq
 * @create: 2020-04-15 11:02
 * @Version: 1.0
 **/
public class ExcelExp implements Serializable {
    
    
	/**
	 * sheet的名称
 	 */

	private String fileName;
	/**
	 * sheet的标题
	 */
	private String[] handers;
	/**
	 * sheet的标题
	 */
	private String titleName;
	/**
	 * sheet里的数据集
	 */
	private List<String[]> dataset;

	public ExcelExp(String titleName,String fileName, String[] handers, List<String[]> dataset) {
    
    
		this.fileName = fileName;
		this.titleName = titleName;
		this.handers = handers;
		this.dataset = dataset;
	}

	public String getFileName() {
    
    
		return fileName;
	}

	public void setFileName(String fileName) {
    
    
		this.fileName = fileName;
	}

	public String[] getHanders() {
    
    
		return handers;
	}

	public void setHanders(String[] handers) {
    
    
		this.handers = handers;
	}

	public List<String[]> getDataset() {
    
    
		return dataset;
	}

	public void setDataset(List<String[]> dataset) {
    
    
		this.dataset = dataset;
	}

	public String getTitleName() {
    
    
		return titleName;
	}

	public void setTitleName(String titleName) {
    
    
		this.titleName = titleName;
	}
}
package org.springblade.common.utils.excel.util;

import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springblade.core.tool.utils.DateUtil;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

/**
 * @program: BladeX
 * @description:
 * @author: lxq
 * @create: 2020-04-15 11:00
 * @Version: 1.0
 **/
public class ExcelExportUtil {
    
    
	/**
	 *
	 * @Title: exportManySheetExcel
	 * @Description: 可生成单个、多个sheet
	 * @param @param file 导出文件路径
	 * @param @param mysheets
	 * @return void
	 * @throws
	 */
	public static void exportManySheetExcel(List<ExcelExp> mysheets,HttpServletResponse response){
    
    
		//创建工作薄
		HSSFWorkbook wb = new HSSFWorkbook();
		CreationHelper createHelper = wb.getCreationHelper();
		List<ExcelExp> sheets = mysheets;
		HSSFCell cell3 = null;
		/*表头样式 start*/
		HSSFCellStyle style = wb.createCellStyle();
		//创建一个居中格式
		style.setAlignment(HorizontalAlignment.CENTER);
		//上下居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		//字体样式
		HSSFFont font1 = wb.createFont();
		font1.setFontName("Arial");
		font1.setFontHeightInPoints((short)16);
		font1.setBold(true);
		style.setFont(font1);
		/*表头样式 end*/
		/*第二个表头样式 start*/
		HSSFCellStyle styleSecond = wb.createCellStyle();
		//创建一个居中格式
		styleSecond.setAlignment(HorizontalAlignment.CENTER);
		//上下居中
		style.setVerticalAlignment(VerticalAlignment.CENTER);
		//设置填充方案
		styleSecond.setFillPattern(FillPatternType.SOLID_FOREGROUND);
		//设置背景色
		styleSecond.setFillBackgroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		//新加的一行
		styleSecond.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
		//字体颜色
		String str = "#FFFFFF";
		//处理把它转换成十六进制并放入一个数
		int[] color=new int[3];
		color[0]=Integer.parseInt(str.substring(1, 3), 16);
		color[1]=Integer.parseInt(str.substring(3, 5), 16);
		color[2]=Integer.parseInt(str.substring(5, 7), 16);
		//自定义颜色
		HSSFPalette palette = wb.getCustomPalette();
		palette.setColorAtIndex(HSSFColor.BLACK.index,(byte)color[0], (byte)color[1], (byte)color[2]);
		//生成一个字体
		HSSFFont font2 = wb.createFont();
		//将自定义的颜色引入进来
		font2.setColor(HSSFColor.BLACK.index);
		HSSFCellStyle cellStyle=wb.createCellStyle();
		cellStyle.setFont(font2);
		font2.setFontHeightInPoints((short)10);
		font2.setFontName("Arial");
		font2.setBold(true);
		//把字体应用到当前的样式
		styleSecond.setFont(font2);
		/*第二个表头样式 end*/
		/*列表数据字体设置 start*/
		HSSFFont font3 = wb.createFont();
		font3.setFontName("Arial");
		font3.setFontHeightInPoints((short) 10);
		HSSFCellStyle styleThree = wb.createCellStyle();
		// 左右居中
		styleThree.setAlignment(HorizontalAlignment.CENTER);
		// 上下居中
		styleThree.setVerticalAlignment(VerticalAlignment.CENTER);
		// 换行
		styleThree.setWrapText(true);
		styleThree.setFont(font3);
		/* 设置为超链接的样式*/
		HSSFCellStyle linkStyle = wb.createCellStyle();
		HSSFFont cellFont= wb.createFont();
		cellFont.setColor(HSSFColor.BLUE.index);
		linkStyle.setFont(cellFont);
		// 上下居中
		linkStyle.setVerticalAlignment(VerticalAlignment.CENTER);
		/*列表数据字体设置 end*/
		//遍历sheets
		for(ExcelExp excel: sheets){
    
    
			//新建一个sheet
			HSSFSheet sheet = wb.createSheet(excel.getFileName());
			//获取该sheet名称
			String[] handers = excel.getHanders();
			//第一个sheet的第一行为标题
			sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, handers.length-1));
			HSSFRow rowFirst = sheet.createRow(0);
			//设置单元格行高
			rowFirst.setHeightInPoints(16);
			rowFirst.setHeight((short) 0x280);
			HSSFCell cell = rowFirst.createCell(0);
			//获取sheet的标题名
			cell.setCellValue(excel.getTitleName());
			cell.setCellStyle(style);
			rowFirst = sheet.createRow(1);
			//写标题
			for(int i=0;i< handers.length;i++){
    
    
				//获取第一行的每个单元格
				HSSFCell cell1 = rowFirst.createCell(i);
				//往单元格里写数据
				cell1.setCellValue(handers[i]);
				//加样式
				cell1.setCellStyle(styleSecond);
				//设置每列的列宽
				sheet.setColumnWidth(i, 4000);
			}
			//写数据集
			List<String[]> dataset = excel.getDataset();
			for(int i=0;i<dataset.size();i++){
    
    
				//获取该对象
				String[] data = dataset.get(i);
				//创建数据行
				rowFirst = sheet.createRow(i+2);
				for(int j=0;j<data.length;j++){
    
    
					//获取第一行的每个单元格
					cell3 = rowFirst.createCell(j);
					//设置对应单元格的值
					cell3.setCellValue(data[j]);
					cell3.setCellStyle(styleThree);
					if("成绩录入数据".equals(excel.getFileName())&&data[1].equals(data[j])){
    
    
						Hyperlink hyperLink =  createHelper.createHyperlink(HyperlinkType.DOCUMENT);
						// "#"表示本文档    "明细页面"表示sheet页名称  "A10"表示第几列第几行
						hyperLink.setAddress("#"+data[1]+"!A1");
						cell3.setHyperlink(hyperLink);
						cell3.setCellValue(data[1]);
						cell3.setCellStyle(linkStyle);
					}
				}
			}
		}
		// 写文件
		try {
    
    
			String  filePath ="D:\\test";
			String  fileName ="\\成绩录入数据"+ DateUtil.format(DateUtil.now(), "yyyyMMddHHmmss") +".xls";
			//输出文件
			File file =new File(filePath);
			if  (!file .exists()  && !file .isDirectory())
			{
    
    
				//如果文件夹不存在则创建
				file.mkdirs();
			}
			FileOutputStream	out = new FileOutputStream(filePath+fileName);
			out.flush();
			wb.write(out);
			out.close();
			getExcel(filePath,fileName,response);
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}
	/**
	 * @Author lxq
	 * @Description TODO 下载指定路径的Excel文件
	 * @Date  2020/4/16 15:20
	 * @Param [url, fileName, response]
	 * @return void
	 **/
	public static void getExcel(String url, String fileName, HttpServletResponse response){
    
    
		try {
    
    
			//1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
			response.setContentType("multipart/form-data");
			//2.设置文件头:最后一个参数是设置下载文件名//支持中文文件名
			response.setHeader("Content-Disposition", "attachment;filename="
				+ new String(fileName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
			//通过文件路径获得File对象
			FileInputStream in = new FileInputStream(url+fileName);
			//3.通过response获取OutputStream对象(out)
			OutputStream out = new BufferedOutputStream(response.getOutputStream());
			int b = 0;
			byte[] buffer = new byte[2048];
			while ((b=in.read(buffer)) != -1){
    
    
				//4.写到输出流(out)中
				out.write(buffer,0,b);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
    
    
			e.printStackTrace();
		}
	}
}

コントローラーで使用

/**
	 * @Author lxq
	 * @Description TODO 批量导出成绩录入数据
	 * @Date  2020/4/15 17:10
	 * @Param [ids]
	 * @return void
	 **/
	@GetMapping("/exportScoreEnter")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "成绩录入数据", notes = "传入scoreEnterId")
	public void expExcel(@RequestParam String ids, HttpServletResponse response) throws IOException {
    
    
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		List<ScoreEnterView> list = null;
		List<ScoreEnterRecord> list2 = null;
		List<ExcelExp> mysheet = new ArrayList<ExcelExp>();
		Long[] idArr = Func.toLongArray(ids);
		String  url  ="D:\\test";
		//成绩录入信息
		list = scoreEnterService.getExportList(idArr);
		//表头
		String[] handers1 = {
    
    "标签", "考试名称", "考试内容", "开始时间", "结束时间", "录入时间", "录入人", "参加人数"};
		//数据
		List<String[]> dataset = new ArrayList<String[]>();
		//对象
		ExcelExp e1 = new ExcelExp("成绩录入数据", "成绩录入数据", handers1, dataset);
		ExcelExp e2 = null;
		for (int i = 0; i < list.size(); i++) {
    
    
			String[] arr = new String[8];
			arr[0] = list.get(i).getTagName() == null ? "" : list.get(i).getTagName();
			arr[1] = list.get(i).getExamTitle() == null ? "" : list.get(i).getExamTitle();
			arr[2] = list.get(i).getTitle() == null ? "" : list.get(i).getTitle();
			arr[3] = list.get(i).getStartDate() == null ? "" : sdf2.format(list.get(i).getStartDate());
			arr[4] = list.get(i).getEndDate() == null ? "" : sdf2.format(list.get(i).getEndDate());
			arr[5] = list.get(i).getEnterTime() == null ? "" : sdf2.format(list.get(i).getEnterTime());
			arr[6] = list.get(i).getEnterPeople() == null ? "" : list.get(i).getEnterPeople();
			arr[7] = list.get(i).getParticipateInNumber() == null ? "" : list.get(i).getParticipateInNumber().toString();
			dataset.add(arr);
		}
		mysheet.add(e1);
		for (int i = 0; i < list.size(); i++) {
    
    
			list2 = scoreEnterRecordService.getByScoreEnterId(Func.toLong(list.get(i).getId()));
			//数据
			List<String[]> dataset2 = new ArrayList<String[]>();
			String[] handers2 = {
    
    "用户姓名", "单位名称", "部门名称", "分数"};
			//查导出成绩详情信息
			for (int j = 0; j < list2.size(); j++) {
    
    
				String[] arr2 = new String[4];
				arr2[0] = list2.get(j).getUserName() == null ? "" : list2.get(j).getUserName();
				arr2[1] = list2.get(j).getFullName() == null ? "" : list2.get(j).getFullName();
				arr2[2] = list2.get(j).getDeptName() == null ? "" : list2.get(j).getDeptName();
				arr2[3] = list2.get(j).getExamScore() == null ? "" : list2.get(j).getExamScore().toString();
				dataset2.add(arr2);
			}
			e2 = new ExcelExp("成绩详情数据", list.get(i).getExamTitle(), handers2, dataset2);
			mysheet.add(e2);
		}
		//生成sheet
		ExcelExportUtil.exportManySheetExcel(mysheet,response);
	}

おすすめ

転載: blog.csdn.net/qq_40660283/article/details/107795033