Problem description

Recently, we encountered the problem of downloading multiple sheets in the project requirement. Using the Hutool tool class, we found that the export always brought a default blank sheet1

// Define the table name at initialization
ExcelWriter writer = new ExcelWriter("d:/aaa.xls"."Table 1");
// Switch sheet, starting at line 0
writer.setSheet("Table 2"); . writer.setSheet("Table 3"); .Copy the code

But it does not seem to meet my requirements for downloading forms, so I used a method to encapsulate a tool class, which is also solved, hereby posted to share with you

/ * * * *@param response
 * @paramFileName Specifies the name of the export file *@paramListMap Content of the exported file. Key is the name of sheet and value is the exported content *@paramMap User-defined title *@param <K>
 * @param <V>
 */
public static <K,V> void exportExcel(HttpServletResponse response, String fileName, Map<K, List<V>> listMap, Map<String, String> map) {
	ExcelWriter writer = cn.hutool.poi.excel.ExcelUtil.getWriter(true);
	Set<Map.Entry<String, String>> entrySet = map.entrySet();
	for (Map.Entry<String, String> entry : entrySet) {
		writer.addHeaderAlias(entry.getKey(), entry.getValue());
	}
	writer.setOnlyAlias(true);
	boolean flag = true;
	for (Map.Entry<K, List<V>> entry : listMap.entrySet()) {
		if (flag) {
			writer.renameSheet(entry.getKey().toString());
			flag = false;
		} else {
			writer.setSheet(entry.getKey().toString());
		}
		writer.write(entry.getValue(), true);
		setSizeColumn(writer.getSheet(), map.size() - 1);
	}
	response.setContentType("application/vnd.ms-excel");
	response.setCharacterEncoding("utf-8");
	ServletOutputStream out = null;
	try {
		fileName = URLEncoder.encode(fileName, "UTF-8");
		response.setHeader("Content-disposition"."attachment; filename=" + fileName + ".xlsx");
		out = response.getOutputStream();
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		writer.flush(out, true); writer.close(); IoUtil.close(out); }}Copy the code

ExcelWriter has a method to change the name of a sheet. Public ExcelWriter renameSheet(String sheetName) changes the name of the sheet the first time you write data and creates the sheet later