主頁 > 後端開發 > 使用EasyExcel實作通用匯出功能

使用EasyExcel實作通用匯出功能

2023-05-20 07:20:55 後端開發

一、環境介紹

  • JDK 1.8+
  • EasyExcel 2.2.7

二、功能實作

此功能可以實作根據傳入自定義的 匯出物體類或Map 進行excel檔案匯出,若根據Map匯出,匯出列的順序可以自定義,
話不多說,直接看代碼

匯出物體類

點擊查看代碼
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.format.DateTimeFormat;
import com.alibaba.excel.annotation.write.style.*;
import com.*.core.tool.utils.DateUtil;
import lombok.Data;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;

import java.time.LocalDateTime;

/**
 * excel匯出物件物體類
 *
 * @author 熱得快炸了
 * @since 2023-4-3
 */
@Data
@HeadStyle(
	borderBottom = BorderStyle.THIN,
	borderLeft = BorderStyle.THIN,
	borderRight = BorderStyle.THIN,
	borderTop = BorderStyle.THIN
)
@ContentStyle(
	borderBottom = BorderStyle.THIN,
	borderLeft = BorderStyle.THIN,
	borderRight = BorderStyle.THIN,
	borderTop = BorderStyle.THIN,
	wrapped = true,
	horizontalAlignment = HorizontalAlignment.LEFT
)
@HeadFontStyle(fontHeightInPoints = (short) 16)
@ContentFontStyle(fontHeightInPoints = (short) 14)
public class ExportDataDTO {

	private static final long serialVersionUID = 1L;
	/**
	 * 序號
	 */
	@ColumnWidth(8)
	@ExcelProperty({"檔案登記簿", "序號"})
	private Integer rowNum;
	/**
	 * 標題
	 */
	@ColumnWidth(50)
	@ExcelProperty({"檔案登記簿", "姓名"})
	private String name;
	/**
	 * 業務型別
	 */
	@ColumnWidth(20)
	@ExcelProperty({"檔案登記簿", "年齡"})
	private String age;
	/**
	 * 業務型別
	 */
	@ColumnWidth(18)
	@ExcelProperty({"檔案登記簿", "性別"})
	private String gender;
}

匯出工具類

點擊查看代碼
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.converters.integer.IntegerNumberConverter;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.*.core.excel.converter.BaseDateConverter;
import com.*.core.excel.listener.DataListener;
import com.*.core.excel.listener.ImportListener;
import com.*.core.excel.strategy.AdjustColumnWidthToFitStrategy;
import com.*.core.excel.support.ExcelException;
import com.*.core.excel.support.ExcelImporter;
import com.*.core.mp.support.Query;
import com.*.core.tool.utils.*;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Nullable;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.util.*;
import java.util.function.BiFunction;

/**
 * Excel工具類
 *
 * @author Chill
 * @apiNote https://www.yuque.com/easyexcel/doc/easyexcel
 */
@Slf4j
public class ExcelUtil {
        /**
	 * 匯出excel
	 *
	 * @param response  回應類
	 * @param fileName  檔案名
	 * @param sheetName sheet名
	 * @param dataList  資料串列
	 * @param clazz     class類
	 * @param <T>       泛型
	 */
	@SneakyThrows
	public static <T> void export(HttpServletResponse response, String fileName, String sheetName, List<T> dataList, Class<T> clazz) {
		response.setContentType("application/vnd.ms-excel");
		response.setCharacterEncoding(Charsets.UTF_8.name());
		fileName = URLEncoder.encode(fileName, Charsets.UTF_8.name());
		response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
		EasyExcel.write(response.getOutputStream(), clazz).sheet(sheetName).doWrite(dataList);
	}


	/**
	 * 根據分頁查詢匯出excel,根據exportClazz類匯出
	 *
	 * @param dto          DTO(分頁查詢物件)
	 * @param resp         回應物件
	 * @param exportClazz  需要匯出的類
	 * @param fileName     檔案名
	 * @param pageDataFunc 分頁查詢方法(須將字典值轉為中文,可呼叫wrapper方法)
	 * @param strategyList 寫入策略集合
	 * @param <D>          DTO類
	 * @param <V>          VO類
	 * @param <E>          匯出類
	 */
	public static <D, V, E> void export(@NotNull D dto,
					    @NotNull HttpServletResponse resp,
					    @NotNull Class<E> exportClazz,
					    @Nullable String fileName,
					    @NotNull BiFunction<D, Query, ? extends IPage<V>> pageDataFunc,
					    @Nullable List<? extends WriteHandler> strategyList) {
		log.info("==================開始匯出excel==================");
		fileName = fileName + ".xlsx";
		String filePath = FileUtil.getTempDirPath() + fileName;
		InputStream in = null;
		OutputStream outp = null;
		File file = new File(filePath);
		try {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			// 構造表格樣式
			List<WriteHandler> strategies = new ArrayList<>();
			if (ObjectUtil.isNotEmpty(strategyList)) {
				strategies.addAll(strategyList);
			} else {
				// 默認匯出樣式
				strategies.addAll(getDefaultStrategy());
			}

			List<List<String>> content = new ArrayList<>();
			// 構建excel寫入物件
			ExcelWriterBuilder writerBuilder = EasyExcel.write(file, exportClazz);
			// 注冊寫入策略
			strategies.forEach(writerBuilder::registerWriteHandler);
			// 注冊物件轉換器
			writerBuilder.registerConverter(new BaseDateConverter.LocalDateTimeConverter());
			writerBuilder.registerConverter(new BaseDateConverter.LocalDateConverter());
			writerBuilder.registerConverter(new BaseDateConverter.LocalTimeConverter());
			writerBuilder.registerConverter(new IntegerNumberConverter());
			ExcelWriter excelWriter = writerBuilder.build();
			// 這里注意 如果同一個sheet只要創建一次
			WriteSheet writeSheet = EasyExcel.writerSheet(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_DATETIME_MINI)).build();
			// 分頁查詢資料
			Query query = new Query();
			query.setSize(500);  //mybatis-plus最大分頁500條
			query.setCurrent(0);
			IPage<V> dataPage = pageDataFunc.apply(dto, query);
			long total = dataPage.getTotal();
			if (total > 50000) {
				throw new ExcelException("資料量過大,請按條件篩選匯出");
			} else if (total <= 0) {
				throw new ExcelException("沒有可以匯出的資料");
			}
			long totalPage = (long) (Math.ceil(((double) total / dataPage.getSize())));
			for (int i = 1; i <= totalPage; i++) {
				List<E> exportList = new ArrayList<>();
				query.setCurrent(i);
				dataPage = pageDataFunc.apply(dto, query);
				List<V> dataList = new ArrayList<>(dataPage.getRecords());
				exportList = BeanUtil.copyProperties(dataList, exportClazz);
				for (int j = 0; j < exportList.size(); j++) {
					E e = exportList.get(j);
					List<Field> fields = getField(e);
					Optional<Field> rowNumField = fields.stream().filter(field -> field.getName().equalsIgnoreCase("rowNum")).findFirst();
					int rowNum = query.getSize() * (i - 1) + (j + 1);
					rowNumField.ifPresent(field -> {
						field.setAccessible(true);
						try {
							field.set(e, rowNum);
						} catch (IllegalAccessException illegalAccessException) {
							illegalAccessException.printStackTrace();
						}
					});
				}
				excelWriter.write(exportList, writeSheet);
			}
			// 千萬別忘記finish 會幫忙關閉流
			excelWriter.finish();

			in = new FileInputStream(filePath);
			outp = resp.getOutputStream();
			//設定請求以及回應的內容型別以及編碼方式
			resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
			resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			outp = resp.getOutputStream();
			//獲取檔案輸入流
			byte[] b = new byte[1024];
			int i = 0;
			//將緩沖區的資料輸出到客戶瀏覽器
			while ((i = in.read(b)) > 0) {
				outp.write(b, 0, i);
			}
			outp.flush();
			log.info("============匯出成功辣!!!!!!!!===========");
		} catch (IOException e) {
			e.printStackTrace();
			log.error("============匯出失敗===========,例外資訊:{}", e.getMessage());
		} finally {
			IoUtil.closeQuietly(in);
			IoUtil.closeQuietly(outp);
			FileUtil.deleteQuietly(file);
		}
	}


	/**
	 * 根據分頁查詢匯出excel,匯出列的順序由<code>exportFields</code>的順序決定
	 *
	 * @param dto          DTO(分頁查詢物件)
	 * @param resp         回應物件
	 * @param exportFields 需要匯出的欄位串列(有序map)
	 * @param fileName     檔案名
	 * @param columnWidth  自定義列寬map,key為列下標,value為寬度,單位:1000=1cm
	 * @param pageDataFunc 分頁查詢方法(須將字典值轉為中文,可呼叫wrapper方法)
	 * @param strategyList 寫入策略集合
	 * @param <D>          DTO泛型
	 * @param <V>          VO泛型
	 */
	public static <D, V> void export(@NotNull D dto,
					 @NotNull HttpServletResponse resp,
					 @NotNull LinkedHashMap<String, String> exportFields,
					 @Nullable String fileName,
					 @NotNull Map<Integer, Integer> columnWidth,
					 @NotNull BiFunction<D, Query, ? extends IPage<V>> pageDataFunc,
					 @Nullable List<? extends WriteHandler> strategyList) {
		log.info("==================開始匯出excel==================");
		fileName = fileName + ".xlsx";
		String filePath = FileUtil.getTempDirPath() + fileName;
		InputStream in = null;
		OutputStream outp = null;
		File file = new File(filePath);
		try {
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			// 構造表格樣式
			List<WriteHandler> strategies = new ArrayList<>();
			if (ObjectUtil.isNotEmpty(strategyList)) {
				strategies.addAll(strategyList);
			} else {
				// 默認匯出樣式
				strategies.addAll(getDefaultStrategy());
			}

			List<List<String>> head = new ArrayList<>();
			List<List<String>> content = new ArrayList<>();
			exportFields.forEach((key, value) -> head.add(Collections.singletonList(value)));
			exportFields.forEach((key, value) -> content.add(Collections.singletonList(key)));
			// 構建excel寫入物件
			ExcelWriterBuilder writerBuilder = EasyExcel.write(file).head(head);
			// 注冊寫入策略
			strategies.forEach(writerBuilder::registerWriteHandler);
			// 注冊物件轉換器
			writerBuilder.registerConverter(new BaseDateConverter.LocalDateTimeConverter());
			writerBuilder.registerConverter(new BaseDateConverter.LocalDateConverter());
			writerBuilder.registerConverter(new BaseDateConverter.LocalTimeConverter());
			writerBuilder.registerConverter(new BaseDateConverter.IntegerConverter());
			ExcelWriter excelWriter = writerBuilder.build();
			// 這里注意 如果同一個sheet只要創建一次
			WriteSheet writeSheet = EasyExcel.writerSheet(DateUtil.format(DateUtil.now(), DateUtil.PATTERN_DATETIME_MINI)).build();
			writeSheet.setColumnWidthMap(ObjectUtil.isNotEmpty(columnWidth) ? columnWidth : null);
			// 分頁查詢資料
			Query query = new Query();
			query.setSize(500);  //mybatis-plus最大分頁500條
			query.setCurrent(0);
			IPage<V> dataPage = pageDataFunc.apply(dto, query);
			long total = dataPage.getTotal();
			if (total > 50000) {
				throw new ExcelException("資料量過大,請按條件篩選匯出");
			} else if (total <= 0) {
				throw new ExcelException("沒有可以匯出的資料");
			}
			long totalPage = (long) (Math.ceil(((double) total / dataPage.getSize())));
			for (int i = 1; i <= totalPage; i++) {
				List<V> dataList = new ArrayList<>();
				List<List<Object>> exportList = new ArrayList<>();
				query.setCurrent(i);
				dataPage = pageDataFunc.apply(dto, query);
				dataList.addAll(dataPage.getRecords());

				for (int j = 0; j < dataList.size(); j++) {
					V dataVO = dataList.get(j);
					List<Object> exportMap = new ArrayList<>();
					for (List<String> s : content) {
						String str = s.get(0);
						List<Field> fieldList = getField(dataVO);
						Field field = fieldList.stream().filter(o -> o.getName().equalsIgnoreCase(str))
							.findFirst().orElseThrow(() -> new RuntimeException(StringUtil.format("找不到欄位:{}", str)));
						field.setAccessible(true);
						exportMap.add(Optional.ofNullable(field.get(dataVO)).orElse(""));
					}
					exportList.add(exportMap);
				}
				excelWriter.write(exportList, writeSheet);
			}
			// 千萬別忘記finish 會幫忙關閉流
			excelWriter.finish();

			in = new FileInputStream(filePath);
			outp = resp.getOutputStream();
			//設定請求以及回應的內容型別以及編碼方式
			resp.setContentType("application/vnd.ms-excel;charset=UTF-8");
			resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			outp = resp.getOutputStream();
			//獲取檔案輸入流
			byte[] b = new byte[1024];
			int i = 0;
			//將緩沖區的資料輸出到客戶瀏覽器
			while ((i = in.read(b)) > 0) {
				outp.write(b, 0, i);
			}
			outp.flush();
			log.info("============匯出成功辣!!!!!!!!===========");
		} catch (IOException | IllegalAccessException e) {
			e.printStackTrace();
			log.error("============匯出失敗===========,例外資訊:{}", e.getMessage());
		} finally {
			IoUtil.closeQuietly(in);
			IoUtil.closeQuietly(outp);
			FileUtil.deleteQuietly(file);
		}
	}

	/**
	 * 默認匯出樣式
	 *
	 * @return
	 */
	private static List<WriteHandler> getDefaultStrategy() {
		List<WriteHandler> writeHandlers = new ArrayList<>();
		/* 默認樣式 */
		// 頭的策略
		WriteCellStyle headStyle = new WriteCellStyle();
		WriteFont headFont = new WriteFont();
		headFont.setFontHeightInPoints((short) 12);
		headStyle.setWriteFont(headFont);

		// 內容的策略
		WriteCellStyle contentStyle = new WriteCellStyle();
		WriteFont contentFont = new WriteFont();
		contentFont.setFontHeightInPoints((short) 12);
		contentStyle.setWriteFont(contentFont);
		// 這個策略是 頭是頭的樣式 內容是內容的樣式 其他的策略可以自己實作
		HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);
		writeHandlers.add(horizontalCellStyleStrategy);

		/* 列寬自適應 */
		writeHandlers.add(new AdjustColumnWidthToFitStrategy());
		return writeHandlers;
	}

	/**
	 * 獲取物件所有欄位(包括父類)
	 *
	 * @param o
	 * @return
	 */
	private static List<Field> getField(Object o) {
		Class c = o.getClass();
		List<Field> fieldList = new ArrayList<>();
		while (c != null) {
			fieldList.addAll(new ArrayList<>(Arrays.asList(c.getDeclaredFields())));
			c = c.getSuperclass();
		}
		return fieldList;
	}
}

列寬自適應策略類

點擊查看代碼

import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description EasyExcel列寬自適應策略類
 * @date: 2023-5-17 10:06
 * @author: 熱得快炸了
 */
public class AdjustColumnWidthToFitStrategy extends AbstractColumnWidthStyleStrategy {
	private Map<Integer, Map<Integer, Integer>> CACHE = new HashMap<>();

	@Override
	protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<CellData> cellDataList, Cell cell, Head head, Integer integer, Boolean isHead) {
		boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
		if (needSetWidth) {
			Map<Integer, Integer> maxColumnWidthMap = CACHE.get(writeSheetHolder.getSheetNo());
			if (maxColumnWidthMap == null) {
				maxColumnWidthMap = new HashMap<>();
				CACHE.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
			}

			Integer columnWidth = this.dataLength(cellDataList, cell, isHead);
			if (columnWidth >= 0) {
				if (columnWidth > 254) {
					columnWidth = 254;
				}

				Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
				if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
					maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
					Sheet sheet = writeSheetHolder.getSheet();
					sheet.setColumnWidth(cell.getColumnIndex(), columnWidth * 200);
				}

				//設定單元格型別
				cell.setCellType(CellType.STRING);
				// 資料總長度
				int length = cell.getStringCellValue().length();
				// 換行數
				int rows = cell.getStringCellValue().split("\n").length;
				// 默認一行高為20
				cell.getRow().setHeightInPoints(rows * 20);
			}
		}
	}

	/**
	 * 計算長度
	 *
	 * @param cellDataList
	 * @param cell
	 * @param isHead
	 * @return
	 */
	private Integer dataLength(List<CellData> cellDataList, Cell cell, Boolean isHead) {
		if (isHead) {
			return cell.getStringCellValue().getBytes().length;
		} else {
			CellData cellData = https://www.cnblogs.com/HotBoom/archive/2023/05/19/cellDataList.get(0);
			CellDataTypeEnum type = cellData.getType();
			if (type == null) {
				return -1;
			} else {
				switch (type) {
					case STRING:
						// 換行符(資料需要提前決議好)
						int index = cellData.getStringValue().indexOf("\n");
						return index != -1 ?
							cellData.getStringValue().substring(0, index).getBytes().length + 1 : cellData.getStringValue().getBytes().length + 1;
					case BOOLEAN:
						return cellData.getBooleanValue().toString().getBytes().length;
					case NUMBER:
						return cellData.getNumberValue().toString().getBytes().length;
					default:
						return -1;
				}
			}
		}
	}
}

分頁查詢工具類

點擊查看代碼
package com.*.core.mp.support;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.experimental.Accessors;

/**
 * 分頁工具
 *
 * @author 熱得快炸了
 */
@Data
@Accessors(chain = true)
@ApiModel(description = "查詢條件")
public class Query {

	/**
	 * 當前頁
	 */
	@ApiModelProperty(value = "https://www.cnblogs.com/HotBoom/archive/2023/05/19/當前頁")
	private Integer current;

	/**
	 * 每頁的數量
	 */
	@ApiModelProperty(value = "https://www.cnblogs.com/HotBoom/archive/2023/05/19/每頁的數量")
	private Integer size;

	/**
	 * 正排序規則
	 */
	@ApiModelProperty(hidden = true)
	private String ascs;

	/**
	 * 倒排序規則
	 */
	@ApiModelProperty(hidden = true)
	private String descs;

}

三、如何使用

1、簡單匯出excel(需要定義匯出物體類)

點擊查看代碼
	public void export(UserDTO userDTO, HttpServletResponse response) {
		List<User> userList = userService.getList(userDTO);
		String fileName = "匯出資料_" + System.currentTimeMillis();
		ExcelUtil.export(response, fileName, "匯出資料", userList, ExportDataDTO.class);
	}

2、根據分頁查詢匯出excel(需要定義匯出物體類)

點擊查看代碼
	public void export(UserDTO userDTO, HttpServletResponse response) {
		String fileName = "匯出資料_" + System.currentTimeMillis();
		ExcelUtil.export(userDTO, response, ExportDataDTO.class, fileName,
			// 將分頁查詢方法作為引數傳入
			(dto, query) -> getPage(query, dto), 
                        // 此處可自定義excel寫入策略
                        null);
	}

3、根據分頁查詢匯出excel,匯出列順序可調整(不需要定義匯出物體類)

點擊查看代碼
	public void export(UserDTO userDTO, HttpServletResponse response) {
		String fileName = "匯出資料_" + System.currentTimeMillis();
                /* exportFields欄位由用戶在前端操作傳入,欄位順序可自由調整
                以下是前端傳入引數樣例
                {            		
                    exportFields: 
                    [
			{rowNum: "序號"},
			{name: "姓名"},
			{age: "年齡"},
			{gender: "性別"}
		    ]
                }
                也可自定義為如下結構
		LinkedHashMap<String, String> exportFields = new LinkedHashMap<>();
		exportFields.put("subject","標題");
		exportFields.put("businessTypeName","業務型別");
		exportFields.put("instantLevel","緊急程度");
		exportFields.put("operator","承辦人");
		exportFields.put("draftTime","擬稿時間");
		exportFields.put("sendOrgName","發文單位");

                自定義列寬示例
		LinkedHashMap<Integer, Integer> columnWidth = new LinkedHashMap<>();
		columnWidth.put(0, 20 * 1000);
		columnWidth.put(1, 8 * 1000);
		columnWidth.put(2, 5 * 1000);
		columnWidth.put(3, 8 * 1000);
		columnWidth.put(4, 8 * 1000);
		columnWidth.put(5, 10 * 1000);
		*/
		List<Map<String, String>> exportFields = userDTO.getExportFields();
		LinkedHashMap<String, String> exports = new LinkedHashMap<>();
		exportFields.forEach(exports::putAll);
		ExcelUtil.export(userDTO, resp, exports, fileName, 
                        // 此引數為自定義列寬時使用, 若傳入null則啟用自適應列寬
                        null,
			this::getPage, null);
	}

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/552926.html

標籤:其他

上一篇:SpringBoot實作WebSocket發送接收訊息 + Vue實作SocketJs接收發送訊息

下一篇:返回列表

標籤雲
其他(159356) Python(38156) JavaScript(25439) Java(18078) C(15229) 區塊鏈(8267) C#(7972) AI(7469) 爪哇(7425) MySQL(7202) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5871) 数组(5741) R(5409) Linux(5340) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4573) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2433) ASP.NET(2403) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) .NET技术(1975) 功能(1967) Web開發(1951) HtmlCss(1940) python-3.x(1918) C++(1918) 弹簧靴(1913) xml(1889) PostgreSQL(1878) .NETCore(1861) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • 【C++】Microsoft C++、C 和匯編程式檔案

    ......

    uj5u.com 2020-09-10 00:57:23 more
  • 例外宣告

    相比于斷言適用于排除邏輯上不可能存在的狀態,例外通常是用于邏輯上可能發生的錯誤。 例外宣告 Item 1:當函式不可能拋出例外或不能接受拋出例外時,使用noexcept 理由 如果不打算拋出例外的話,程式就會認為無法處理這種錯誤,并且應當盡早終止,如此可以有效地阻止例外的傳播與擴散。 示例 //不可 ......

    uj5u.com 2020-09-10 00:57:27 more
  • Codeforces 1400E Clear the Multiset(貪心 + 分治)

    鏈接:https://codeforces.com/problemset/problem/1400/E 來源:Codeforces 思路:給你一個陣列,現在你可以進行兩種操作,操作1:將一段沒有 0 的區間進行減一的操作,操作2:將 i 位置上的元素歸零。最終問:將這個陣列的全部元素歸零后操作的最少 ......

    uj5u.com 2020-09-10 00:57:30 more
  • UVA11610 【Reverse Prime】

    本人看到此題沒有翻譯,就附帶了一個自己的翻譯版本 思考 這一題,它的第一個要求是找出所有 $7$ 位反向質數及其質因數的個數。 我們應該需要質數篩篩選1~$10^{7}$的所有數,這里就不慢慢介紹了。但是,重讀題,我們突然發現反向質數都是 $7$ 位,而將它反過來后的數字卻是 $6$ 位數,這就說明 ......

    uj5u.com 2020-09-10 00:57:36 more
  • 統計區間素數數量

    1 #pragma GCC optimize(2) 2 #include <bits/stdc++.h> 3 using namespace std; 4 bool isprime[1000000010]; 5 vector<int> prime; 6 inline int getlist(int ......

    uj5u.com 2020-09-10 00:57:47 more
  • C/C++編程筆記:C++中的 const 變數詳解,教你正確認識const用法

    1、C中的const 1、區域const變數存放在堆疊區中,會分配記憶體(也就是說可以通過地址間接修改變數的值)。測驗代碼如下: 運行結果: 2、全域const變數存放在只讀資料段(不能通過地址修改,會發生寫入錯誤), 默認為外部聯編,可以給其他源檔案使用(需要用extern關鍵字修飾) 運行結果: ......

    uj5u.com 2020-09-10 00:58:04 more
  • 【C++犯錯記錄】VS2019 MFC添加資源不懂如何修改資源宏ID

    1. 首先在資源視圖中,添加資源 2. 點擊新添加的資源,復制自動生成的ID 3. 在解決方案資源管理器中找到Resource.h檔案,編輯,使用整個專案搜索和替換的方式快速替換 宏宣告 4. Ctrl+Shift+F 全域搜索,點擊查找全部,然后逐個替換 5. 為什么使用搜索替換而不使用屬性視窗直 ......

    uj5u.com 2020-09-10 00:59:11 more
  • 【C++犯錯記錄】VS2019 MFC不懂的批量添加資源

    1. 打開資源頭檔案Resource.h,在其中預先定義好宏 ID(不清楚其實ID值應該設定多少,可以先新建一個相同的資源項,再在這個資源的ID值的基礎上遞增即可) 2. 在資源視圖中選中專案資源,按F7編輯資源檔案,按 ID 型別 相對路徑的形式添加 資源。(別忘了先把檔案拷貝到專案中的res檔案 ......

    uj5u.com 2020-09-10 01:00:19 more
  • C/C++編程筆記:關于C++的參考型別,專供新手入門使用

    今天要講的是C++中我最喜歡的一個用法——參考,也叫別名。 參考就是給一個變數名取一個變數名,方便我們間接地使用這個變數。我們可以給一個變數創建N個參考,這N + 1個變數共享了同一塊記憶體區域。(參考型別的變數會占用記憶體空間,占用的記憶體空間的大小和指標型別的大小是相同的。雖然參考是一個物件的別名,但 ......

    uj5u.com 2020-09-10 01:00:22 more
  • 【C/C++編程筆記】從頭開始學習C ++:初學者完整指南

    眾所周知,C ++的學習曲線陡峭,但是花時間學習這種語言將為您的職業帶來奇跡,并使您與其他開發人員區分開。您會更輕松地學習新語言,形成真正的解決問題的技能,并在編程的基礎上打下堅實的基礎。 C ++將幫助您養成良好的編程習慣(即清晰一致的編碼風格,在撰寫代碼時注釋代碼,并限制類內部的可見性),并且由 ......

    uj5u.com 2020-09-10 01:00:41 more
最新发布
  • 使用EasyExcel實作通用匯出功能

    ## 一、環境介紹 * JDK 1.8+ * EasyExcel 2.2.7 ## 二、功能實作 此功能可以實作根據傳入自定義的 匯出物體類或Map 進行excel檔案匯出。若根據Map匯出,匯出列的順序可以自定義。 **話不多說,直接看代碼** ### 匯出物體類 點擊查看代碼 ``` impor ......

    uj5u.com 2023-05-20 07:20:55 more
  • SpringBoot實作WebSocket發送接收訊息 + Vue實作SocketJs接收發

    # SpringBoot實作WebSocket發送接收訊息 + Vue實作SocketJs接收發送訊息 ### 參考: 1、https://www.mchweb.net/index.php/dev/887.html 2、https://itonline.blog.csdn.net/article/d ......

    uj5u.com 2023-05-20 07:20:34 more
  • 【K哥爬蟲普法】你很會寫爬蟲嗎?10秒搶票、10秒入獄,了解一下?

    ![01](https://img2023.cnblogs.com/other/2501174/202305/2501174-20230519165542353-407579772.png) > 我國目前并未出臺專門針對網路爬蟲技術的法律規范,但在司法實踐中,相關判決已屢見不鮮,K 哥特設了“K哥爬 ......

    uj5u.com 2023-05-20 07:09:16 more
  • 從零玩轉Nginx

    01【熟悉】實際開發中的問題? 現在我們一個專案跑在一個tomcat里面 當一個tomcat無法支持高的并發量時。可以使用多個tomcat 那么這多個tomcat如何云分配請求 |-nginx 02【熟悉】服務器概述 1,目前常見的web服務器 1,Apache(http://httpd.apach ......

    uj5u.com 2023-05-19 14:45:43 more
  • 驅動開發:通過應用堆實作多次通信

    在前面的文章`《驅動開發:運用MDL映射實作多次通信》`LyShark教大家使用`MDL`的方式靈活的實作了內核態多次輸出結構體的效果,但是此種方法并不推薦大家使用原因很簡單首先內核空間比較寶貴,其次內核里面不能分配太大且每次傳出的結構體最大不能超過`1024`個,而最終這些記憶體由于無法得到更好的釋... ......

    uj5u.com 2023-05-19 14:42:56 more
  • Linux網路編程:socket & pthread_create()多執行緒 實作clients/s

    一、問題引入 Linux網路編程:socket & fork()多行程 實作clients/server通信 隨筆介紹了通過fork()多行程實作了服務器與多客戶端通信。但除了多行程能實作之外,多執行緒也是一種實作方式。 重要的是,多行程和多執行緒是涉及作業系統層次。隨筆不僅要利用pthread_cre ......

    uj5u.com 2023-05-19 14:28:36 more
  • Windows10安裝Jmeter(圖文教程)

    Apache JMeter是Apache組織開發的基于Java的壓力測驗工具。用于對軟體做壓力測驗,它最初被設計用于Web應用測驗,但后來擴展到其他測驗領域。 它可以用于測驗靜態和動態資源,例如靜態檔案、Java 小服務程式、CGI 腳本、Java 物件、資料庫、FTP 服務器, 等等。JMeter ......

    uj5u.com 2023-05-19 14:23:03 more
  • 37基于java的職工管理系統設計與實作

    基于java的職工管理系統設計與實作,員工管理系統,企業員工管理系統,公司員工管理系統,企業人事管理系統,基于java職工管理系統,前后端分離,員工考勤管理系統,職工獎懲管理系統,職員合同管理,HR管理系統,人事HR管理系統。 ......

    uj5u.com 2023-05-19 14:22:48 more
  • 實用教程丨如何將實時資料顯示在前端電子表格中(一)

    Author Alex Zhang Category SpreadJS Tags SpreadJS,前端電子表格,實時資料,RealTime Data 前言 資料(包括股票、天氣和體育比分)在不斷更新為新資訊時最為有用。SpreadJS是一個非常通用的 JavaScript 電子表格組件,它還可以輕 ......

    uj5u.com 2023-05-19 14:22:28 more
  • 希望所有計算機專業同學都知道這些老師

    C語言教程——翁凱老師、赫斌 翁愷老師是土生土長的浙大碼農,從本科到博士都畢業于浙大計算機系,后來留校教書,一教就是20多年。 翁愷老師的c語言課程非常好,講解特別有趣,很適合初學者學習。 郝斌老師的思路是以初學者的思路來思考的,非常適合小白,你不理解的問題,基本上他都會詳細說一下。 C++——侯捷 ......

    uj5u.com 2023-05-19 14:20:14 more