vue 页面表格数据导成 Excel 文件功能

前端工具文件

excelUtil.js

// export excel file relative

export function exportExcelFile(reqParams){
  // 请求 Excel 文件
  console.log('start download ----');
  console.log(reqParams);

  return new Promise((resolve, reject) => {
    if(!reqParams || !reqParams.url || !reqParams.method) {
      return reject('params error');
    }
    const xhr = new XMLHttpRequest();
    xhr.responseType = "arraybuffer";
    xhr.open(reqParams.method, reqParams.url, true);
    xhr.onload = () => {
      console.log(xhr);
      let tt = exportExcelFileHandleResult(xhr);
      if(!tt || tt.status !== 200) {
        reject(tt.msg);
      } else {
        resolve();
      }
    };
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
    let params = '';
    if(reqParams.params) {
      params = Object.keys(reqParams.params).map(function (key) {
        return encodeURIComponent(key) + "=" + encodeURIComponent(reqParams.params[key]);
      }).join("&");
    }
    console.log(params);
    xhr.send(params);
  });
}

function exportExcelFileHandleResult(xhr) {
  let result = {
    status: 200,
    msg: ''
  };
  // 处理下载 Excel 文件时返回的结果
  // 判断是否出错 (如:下载行数超过最大值)
  let statusCode = xhr.status;  // 状态码
  if(statusCode !== 200 && statusCode !== 201) {  // 如果正确返回,则为 200 OK 或者 201 CREATED
    let errMsg = xhr.getResponseHeader("message");  //  自定义响应头参数,传递提示信息
    result.status = statusCode;
    result.msg = errMsg ? (decodeURI(errMsg).replace(/\+/gi, ' ').replace(/%2B/gi, '+')) : 'Server Error';
    return result;
  }

  // 取得后台传来的文件名
  let filename = xhr.getResponseHeader("Content-disposition");
  if(!filename) {  // 后台有可能返回 Null , 导致 filename 为空 (这儿后台应该处理)
    result.status = 500;
    result.msg = 'Server Error';
    return result;
  }
  filename = filename.substring(filename.indexOf("filename=\"")+10, filename.length-1);
  filename = decodeURI(filename).replace(/\+/gi, ' ').replace(/%2B/gi, '+');  // 后台编码了
  console.log("文件名:" + filename);

  // 取得文件主体
  // .xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
  // .xls application/vnd.ms-excel
  let blob = new Blob(
      [xhr.response],
      {type:"application/vnd.ms-excel"}
  );
  let objUrl = URL.createObjectURL(blob);
  let link = document.createElement('a');
  link.style = "display:none;";
  link.href = objUrl;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  return result;
}

前端请求示例

		import {exportExcelFile} from "../../../utils/excelUtil";

		// 导出Excel
		handleExportExcel(){
			// 需要的参数
			let reqParams = {
				url: '/api/exportExcel.do',
				method: 'POST',
				params: {...this.listQuery}  // this.listQuery = {currentPage: 1, pageSize: 10 , isAll: false};
			};
			exportExcelFile(reqParams).then(() => {
				this.exportExcelDisabled = false;
			}).catch(msg => {
				this.$message.error(msg);
			});
		},	

Java工具类

package com.guagua.whse.common.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.VerticalAlignment;
import jxl.format.*;
import jxl.write.Number;
import jxl.write.*;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.Boolean;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.ResourceBundle;

public class ExcelUtil {

	private static final String baseName = "excelModel";
	// 类加载时就读取 properties 文件
	public static ResourceBundle rb = readExcelModelProperties(baseName);

	/**
	 * 【一般方法】
	 *
	 * 通过属性名,调用该属性名对应的 Get 方法
	 * @param ob  对象
	 * @param fieldName  字段名
	 * @return
	 * @throws Exception
	 */
	public static Object getGetMethodValue(Object ob, String fieldName) {
		// getUsername 首字母大写
		String getSuffix = fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);

		try {
			Method method = ob.getClass().getMethod("get"+getSuffix);
			return method.invoke(ob);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 【一般方法】
	 *
	 * 读取 properties 文件
	 *
	 * @param baseName  baseName_zh_CN.properties
	 *
	 */
	public static ResourceBundle readExcelModelProperties(String baseName)  {
		try {
			return ResourceBundle.getBundle(baseName, Locale.getDefault());
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 【一般方法】
	 *
	 * 取得一个属性值
	 * @param key
	 * @return
	 */
	public static String getItemString(String key) {
		if(rb == null) {
			rb = readExcelModelProperties(baseName);
		}
		try {
			if(rb == null) return null;
			return new String(rb.getString(key).getBytes("ISO-8859-1"),"UTF-8");
		} catch (Exception e) {
			return null;
		}
	}


	// -------------------  Excel 相关 ------------------

	/**
	 * 根据颜色名称取得 Colour 对象
	 * @param colourName 颜色字符串名称
	 * @param defaultColour 默认颜色
	 * @return
	 */
	public static Colour getColour(String colourName, Colour defaultColour) {
		Colour colour = null;
		try {
			Field field = Colour.class.getField(colourName);
			colour = (Colour) field.get(Colour.class);
			return colour;
		} catch (NoSuchFieldException | IllegalAccessException e) {
			e.printStackTrace();
			return defaultColour;
		}
	}

	/**
	 * 根据 json 创建一个单元格样式
	 * TODO 需要处理,设置更多的单元格样式
	 * @param json 该单元格对应样式参数,类似 css
	 * @return
	 */
	public static WritableCellFormat getCellFormat(JSONObject json) {
		try {
			WritableFont font = new WritableFont(WritableFont.createFont(
					json.getString("fontName")),
					json.getInteger("fontSize"),
					(json.getBoolean("bold") ? WritableFont.BOLD : WritableFont.NO_BOLD),
					json.getBoolean("italic"));

			if(json.getString("underline").equals("NO_UNDERLINE")) {  // 下划线, 待处理
				font.setUnderlineStyle(UnderlineStyle.NO_UNDERLINE);
			}
			font.setColour(getColour(json.getString("color"), Constants.ExcelModel.FONT_COLOUR)); // 颜色

			WritableCellFormat cellFormat = new WritableCellFormat(font);
			cellFormat.setBackground(getColour(json.getString("backgroundColor"), Constants.ExcelModel.BACKGROUND_COLOUR));  // 背景颜色

			if(json.getString("align").equals("CENTRE")) {  // 水平对齐,待处理
				cellFormat.setAlignment(Alignment.CENTRE);
			}
			if(json.getString("verticalAlign").equals("CENTRE")) {  // 垂直对齐,待处理
				cellFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
			}
			// 边框,待处理
			String borderPosition = json.getString("borderPosition");
			String borderStyle = json.getString("borderStyle");
			String borderColor = json.getString("borderColor");
			cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.UNKNOWN);

			return cellFormat;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 给一个单元格填入内容
	 * @param ws  工作表对象
	 * @param rowIndex 当前行索引
	 * @param tbCellFormat  当前单元格样式
	 * @param colItem 当前单元格对应的参数
	 * @param object 当前行对应数据对象
	 * @return
	 */
	public static WritableSheet setCellData(WritableSheet ws, int rowIndex, WritableCellFormat tbCellFormat, JSONObject colItem, Object object)
			throws InvocationTargetException, IllegalAccessException, WriteException {

		int colIndex = colItem.getInteger("index");  // 当前列在工作表中的列索引
		String fieldType = colItem.getString("fieldType");  // 该列显示类型 String, Number(Double), Date
		if(fieldType == null) fieldType = "String";  // 默认值

		String fieldName = colItem.getString("fieldName");  // 当前列对应数据对象的属性名 username
		Object fieldValue = getGetMethodValue(object, fieldName);  // 当前列对应数据对象的值 getUsername()

		WritableCell cell = null;  // 需要填充到单元格的内容

		// 根据单元格中显示类型填充数据
		if(fieldValue == null) {  // 没有值,单元格为空
			cell = new Blank(colIndex, rowIndex, tbCellFormat);
		}
		else {
			// fieldValue 是 Object ,需要按照不同类型进行转换
			if(fieldType.equals("Number")) {  // 单元格要求数字
				Double value = null;
				if(fieldValue instanceof java.lang.Number) {  // 值本来是数字类型
					value = ((java.lang.Number) fieldValue).doubleValue();
				}
				else if(fieldValue instanceof Date) {  // 值是日期,转换为毫秒值
					value = (double) ((Date) fieldValue).getTime();
				}
				else {  // 其它所有类型,主要是 String
					value = Double.parseDouble(fieldValue.toString());
				}
				cell = new Number(colIndex, rowIndex, value, tbCellFormat);
			}
			else if(fieldType.equals("Date")) {  // 单元格要求日期
				Date value = null;
				if(fieldValue instanceof Date) {  // 本来就是日期
					value = (Date) fieldValue;
				} else {  // 其它各种类型,暂时不转换
					value = null;
				}
				cell = new DateTime(colIndex, rowIndex, value, tbCellFormat);
			}
			else {  // 剩下的一律当做 String
				String value = null;
				if(fieldValue instanceof Date) {  // 字符串日期,需要样式
					String datePattern = colItem.getString("pattern");  // 样式 yyyy-MM-dd
					value = DateUtils.toDateFormatString((Date)fieldValue, datePattern);
				} else {
					value = fieldValue.toString();
				}
				cell = new Label(colIndex, rowIndex, value, tbCellFormat);
			}
		}

		ws.addCell(cell);
		return ws;
	}

	/**
	 * 对一个简单表格 SIMPLE_TABLE 类型的工作表设置样式 (表头)
	 * @param style
	 * @param ws
	 * @return
	 */
	public static WritableSheet setSheetStyleOfSimpleTable(JSONObject style, WritableSheet ws) throws WriteException {
		// 取得表头样式参数
		JSONObject tableHead = style.getJSONObject("tableHead");

		// 单元格样式
		WritableCellFormat thCellFormat = null;

		if(tableHead != null) {  // 有配置表头单元格样式
			thCellFormat = getCellFormat(tableHead);
		} else {
			tableHead = new JSONObject();  // 默认的表头位置、高度
			tableHead.put("rowIndex", 0);
			tableHead.put("height", 400);
		}

		if(thCellFormat == null) {  // 单元格样式创建失败,使用默认
			thCellFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont("微软雅黑"), 12, WritableFont.BOLD));
		}

		// 表头的位置及高度
		ws.setRowView(tableHead.getInteger("rowIndex"), tableHead.getInteger("height"));
		// 表头所在行索引
		int thRowIndex = tableHead.getInteger("rowIndex");

		// 列数据样式
		JSONArray tableColumnArr = style.getJSONArray("tableColumn");  // 这个必须有,需要设置表头
		// 填充表头、设置列宽度
		for(int i = 0; i < tableColumnArr.size(); i++) {
			JSONObject colItem = tableColumnArr.getJSONObject(i);  // 包含一列表头的内容、宽度、样式
			int colIndex = colItem.getInteger("index");  // 列坐标
			// 填充表头单元格
			// Label(列索引, 行索引, 字符串, 单元格样式)
			ws.addCell(new Label(colIndex, thRowIndex, colItem.getString("title"), thCellFormat));

			// 设置列宽度
			ws.setColumnView(colIndex, colItem.getInteger("width"));
		}
		return ws;
	}

	/**
	 * 对一个简单表格 SIMPLE_TABLE 类型的工作表填充数据 (表主体)
	 * @param style
	 * @param ws
	 * @return
	 */
	public static WritableSheet fillSheetStyleOfSimpleTable(JSONObject style, WritableSheet ws, List<?> dataList)
			throws IllegalAccessException, WriteException, InvocationTargetException {
		// 表主体单元格样式参数
		JSONObject tableBody = style.getJSONObject("tableBody");
		// 单元格样式
		WritableCellFormat tbCellFormat = null;

		if(tableBody != null) {  // 有配置表主体单元格样式
			tbCellFormat = getCellFormat(tableBody);
		} else {
			tableBody = new JSONObject();  // 默认的
			tableBody.put("startRowIndex", 1);
		}

		if(tbCellFormat == null) {  // 单元格样式创建失败,使用默认
			tbCellFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont("微软雅黑"), 10));
		}

		// 列数据样式
		JSONArray tableColumnArr = style.getJSONArray("tableColumn");  // 必须有

		// 表主体开始行索引
		int tbStartRowIndex = tableBody.getInteger("startRowIndex");
		// 添加表主体数据
		for (int ri = 0; ri < dataList.size(); ri++) {
			Object object = dataList.get(ri);  // 该行数据对象

			int rowIndex = tbStartRowIndex + ri;  // sheet 中当前行位置索引

			// 遍历配置文件中设定的列,即生成的表格共有多少列
			for(int ci = 0; ci < tableColumnArr.size(); ci++) {
				JSONObject colItem = tableColumnArr.getJSONObject(ci); // 一列的样式数据
				setCellData(ws, rowIndex, tbCellFormat, colItem, object);
			}
		} // end dataList

		return ws;
	}

	/**
	 * 根据工作表类型,给一个工作表填入内容
	 * @param style 工作表样式参数
	 * @param ws 工作表对象
	 * @return
	 */
	public static WritableSheet fillSheet(JSONObject style, WritableSheet ws, List<?> dataList)
			throws WriteException, IllegalAccessException, InvocationTargetException {
		if(style.getString("type").equals("SIMPLE_TABLE")) {  // 目前只支持 SIMPLE_TABLE
			// 设置工作表样式(主要是表头)
			setSheetStyleOfSimpleTable(style, ws);
			// 表主体填入数据
			fillSheetStyleOfSimpleTable(style, ws, dataList);
		}

		return ws;
	}

	/**
	 * 处理下载 Excel 文件名,不包含 后缀
	 * @return
	 */
	public static String resetFilename(JSONObject json) {
		// 文件名(不含后缀),其中有需要替换的模板,类似 Hello {0} ! ,需要将 {0} 替换
		String filenamePrefix = json.getString("filenamePrefix");

		// 替换的数组,全部是字符串,需要转换
		JSONArray paramJson = json.getJSONArray("paramArr");
		// 转换后
		Object[] params = new Object[paramJson.size()];
		for(int i = 0; i < paramJson.size(); i++) {
			String tmp = paramJson.getString(i);
			if(tmp.startsWith("DATE_NOW_")) {  // 表示用当前日期替换,后面是格式 DATE_NOW_yyyyMMddhhmmss
				params[i] = DateUtils.toDateFormatString(new Date(), tmp.substring(9));
			} else {
				params[i] = tmp;
			}
		}

		return MessageFormat.format(filenamePrefix, params);  // 填充 filenamePrefix 中的模板
	}

	/**
	 * 创建 Excel 对象
	 * @param dataList 数据
	 * @param json 样式参数
	 * @param wwb  工作表对象
	 * @return
	 * @throws Exception
	 */
	public static WritableWorkbook createExcel(List<?> dataList, JSONObject json, WritableWorkbook wwb) throws Exception {
		// 1. 准备参数
		JSONArray sheetNameArr = json.getJSONArray("sheetNameArr");  // 工作表 名称数组,即共有多少个工作表
		JSONArray styleJsonArr = json.getJSONArray("style");  // 工作表 样式数组, sheetNameArr 和 styleJsonArr 一一对应

		// 2. 遍历工作表名称数组
		for(int sheetIndex = 0; sheetIndex < sheetNameArr.size(); sheetIndex++) {

			// 3. 创建工作表
			WritableSheet ws = wwb.createSheet(sheetNameArr.getString(sheetIndex), sheetIndex);
			// 当前工作表样式参数
			JSONObject style = styleJsonArr.getJSONObject(sheetIndex);

			// 4. 根据工作表类型,进行不同的样式设置,并填入数据
			fillSheet(style, ws, dataList);

			wwb.write(); // 每个表完成时,写出
		}

		// 5. Excel 表完成,写入文件
		wwb.write();
		return wwb;
	}

	/**
	 * 使用内存创建 Excel 对象,并生成字节数组
	 * @param dataList
	 * @param json
	 * @param os
	 * @return
	 * @throws IOException
	 */
	public static byte[] createExcel(List<?> dataList, JSONObject json, ByteArrayOutputStream os) {
		WritableWorkbook wwb = null;
		try {
			wwb = Workbook.createWorkbook(os);
			createExcel(dataList, json, wwb);
			os.flush();
			wwb.close();  // 关闭之后才能输出字节数组
			wwb = null;
			return os.toByteArray();
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if (wwb != null) {
				try {
					wwb.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 创建 Excel ,生成的 Excel 文件位于 File, 或者 ByteArrayOutputStream (内存)
	 * @return
	 */
	public static byte[] createExcel(List<?> dataList, JSONObject json, File file) {
		WritableWorkbook wwb = null; // Excel 文件处理对象
		try {
			wwb = Workbook.createWorkbook(file);
			createExcel(dataList, json, wwb);
			wwb.close();  // 关闭之后才能输出字节数组
			wwb = null;
			return FileUtils.readFileToByteArray(file);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if (wwb != null) {
				try {
					wwb.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}


	/**
	 * 创建发送对象
	 * @return
	 */
	public static ResponseEntity<byte[]> createResponseEntity(byte[] body, String filenamePrefix, String filenameSuffix) {
		HttpHeaders headers = new HttpHeaders();

		// 构造发送文件名
		String fileName = filenamePrefix + filenameSuffix;
		String name = null;  // 中文乱码
		try {
			name = URLEncoder.encode(fileName, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			name = fileName;
		}

		// 设置响应头
		headers.setContentDispositionFormData("attachment", name);
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

		return new ResponseEntity<byte[]>(body, headers, HttpStatus.CREATED);
	}

	/**
	 * 导出 Excel 文件
	 */
	public static ResponseEntity<byte[]> exportExcel(List<?> dataList, String type) {

		// 1. 取得配置文件
		String str = getItemString(type);
		JSONObject json = JSONObject.parseObject(str);

		String filenamePrefix = resetFilename(json);  // 文件名,不含后缀
		String filenameSuffix = json.getString("filenameSuffix");  // 文件名后缀

		// 2. 【一种即可】创建输出流来存放生成的 Excel 对象   File, ByteArrayOutputStream
		File file = null;
		//ByteArrayOutputStream os = null;
		try {
			file = File.createTempFile(filenamePrefix, filenameSuffix);  // File 作为输出流
			//os = new ByteArrayOutputStream();  // 内存 作为输出流

			// 创建 Excel
			byte[] body = createExcel(dataList, json, file);
			//byte[] body = createExcel(dataList, json, os);

			// 3. 发送
			return createResponseEntity(body, filenamePrefix, filenameSuffix);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if (file != null) {
				file.delete();
			}
		}
	}

	/**
	 * 当出现错误,无法下载时(如数据量过大),发送提示信息
	 * @return
	 */
	public static ResponseEntity<byte[]> sendErrorMessage(String msg) {
		HttpHeaders headers = new HttpHeaders();
		//headers.set("message", new String(Constants.ExcelModel.MAX_COUNT_MSG.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
		String message = null;
		try {
			message = URLEncoder.encode(msg, "UTF-8");  // 中文乱码
		} catch (UnsupportedEncodingException e) {
			message = msg;
		}
		headers.set("message", message);
		headers.setContentType(MediaType.TEXT_PLAIN);
		return new ResponseEntity<byte[]>(msg.getBytes(StandardCharsets.UTF_8), headers, HttpStatus.BAD_REQUEST);

	}

	// --------------- 没有 配置文件 时创建 -----------------

	// 用到前面的 : createResponseEntity()

	/**
	 * 没有配置文件时,导出 Excel 表格
	 *
	 * 此时,表格中包含 list 中对象的所有 拥有 get 方法的属性。 很可能会显示不应该显示的内容。
	 * @param dataList
	 * @return
	 */
	public static ResponseEntity<byte[]> exportExcel(List<?> dataList) {
		File file = null;
		WritableWorkbook wwb = null;

		String filenamePrefix = DateUtils.toDateFormatString(new Date(), "yyyyMMddHHmmss");
		String filenameSuffix = ".xls";

		try {
			file = File.createTempFile(filenamePrefix, filenameSuffix);
			wwb = Workbook.createWorkbook(file);
			WritableSheet ws = wwb.createSheet("sheet1", 0);

			WritableCellFormat thCellFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont("微软雅黑"), 12, WritableFont.BOLD));
			WritableCellFormat tbCellFormat = new WritableCellFormat(new WritableFont(WritableFont.createFont("微软雅黑"), 10));
			ws.setRowView(0, 500);

			boolean thFilled = false;  // 表头是否已经填入
			for (int ri = 0; ri < dataList.size(); ri++) {  // 行
				Object object = dataList.get(ri);
				int rowIndex = ri + 1;  // 行索引(第一行为表头)

				Field[] fields = object.getClass().getDeclaredFields();  // 所有属性
				int ci = 0; // 列索引
				for(Field field : fields) {
					field.setAccessible(true);  // 允许访问私有属性
					String fieldName = field.getName();  // 属性名
					String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
					Method method = null;  // 属性对应 get 方法
					try {
						method = object.getClass().getMethod(getMethodName);
					} catch (NoSuchMethodException e) { // 没有对应的 get 方法 跳过
						e.printStackTrace();
						continue;
					}
					Object fieldValue = null;  // get 返回值
					try {
						fieldValue = method.invoke(object);
					} catch (Exception e) {
						e.printStackTrace();
					}

					// 填入表头(只填一次)
					if(!thFilled) {
						ws.addCell(new Label(ci, 0, fieldName, thCellFormat));
					}

					// 填入表主体
					WritableCell cell = null;  // 种类: Blank, Boolean, jxl.write.biff.CellValue, DateTime, Formula, Label, Number
					if(fieldValue == null) {  // 没有值,单元格为空
						cell = new Blank(ci, rowIndex, tbCellFormat);
					}
					else if(fieldValue instanceof java.lang.Number) {  // 数字
						cell = new Number(ci, rowIndex, ((java.lang.Number) fieldValue).doubleValue(), tbCellFormat);
					}
					else if(fieldValue instanceof Date) {  // 日期
						cell = new Label(ci, rowIndex, DateUtils.toDateFormatString((Date) fieldValue, DateUtils.YYYY_MM_DD_HH_MM_SS), tbCellFormat);
					}
					else if(fieldValue instanceof Boolean) {  // Boolean
						cell = new jxl.write.Boolean(ci, rowIndex, (Boolean) fieldValue, tbCellFormat);
					}
					else {  // 其余一律作为 String
						cell = new Label(ci, rowIndex, fieldValue.toString(), tbCellFormat);
					}
					ws.addCell(cell);

					ci++;  // 下一列
				}

				thFilled = true;  // 在填入第一行数据时,填写了表头,之后就不用了
			}

			wwb.write();
			wwb.close();
			wwb = null;
			byte[] body = FileUtils.readFileToByteArray(file);
			return createResponseEntity(body, filenamePrefix, filenameSuffix);
		}
		catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		finally {
			if (wwb != null) {
				try {
					wwb.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (file != null) {
				file.delete();
			}
		}
	}


}

后台业务代码

 public ResponseEntity<byte[]> exportGoodsStock(GoodsStock goodsStock, Page<GoodsStock> page, Boolean isAll) {
        int count = goodsStockMapper.count(goodsStock);  // 查询结果数量
        if(count > Constants.ExcelModel.maxCount){  // 超过可下载的最大数
            return ExcelUtil.sendErrorMessage(Constants.ExcelModel.MAX_COUNT_MSG);
        }

        List<GoodsStock> dataList = null;
        if(count >0 ){
            if(isAll) dataList = goodsStockMapper.queryGoodsStock(goodsStock);      // 全部数据
            else dataList = goodsStockMapper.queryGoodsStockPage(goodsStock, page); // 单页数据
        }
        return ExcelUtil.exportExcel(dataList, Constants.ExcelModel.LIST_GOODS_STOCK_EXCEL);
        										// ↑ 第二个参数是静态常量文件中的数据,对应下面配置文件  public final static String LIST_GOODS_STOCK_EXCEL = "LIST_GOODS_STOCK_EXCEL";
    }

后台配置文件

(需配置 Excel 文件中的各种样式、格式等,java工具类是根据此配置文件去生成对应的 Excel 文件)
excelModel.properties

# 货物库存信息列表
LIST_GOODS_STOCK_EXCEL = {"filenamePrefix":"货物库存信息列表_{0}","filenameSuffix":".xls","paramArr":["DATE_NOW_yyyyMMddHHmmss"],"sheetNameArr":["货物库存信息列表"],"style":[{"type":"SIMPLE_TABLE","tableHead":{"fontName":"微软雅黑","fontSize":12,"bold":true,"italic":false,"underline":"NO_UNDERLINE","color":"BLACK","backgroundColor":"PALE_BLUE","align":"CENTRE","verticalAlign":"CENTRE","height":500,"rowIndex":0},"tableBody":{"fontName":"微软雅黑","fontSize":10,"bold":false,"italic":false,"underline":"NO_UNDERLINE","color":"BLACK","backgroundColor":"WHITE","align":"","verticalAlign":"CENTRE","height":0,"startRowIndex":1},"tableColumn":[{"index":0,"width":10,"title":"货位名称","fieldName":"warehouseName","fieldType":"String"},{"index":1,"width":30,"title":"物品名称C","fieldName":"goodsName","fieldType":"String"},{"index":2,"width":15,"title":"批次号","fieldName":"batchNo","fieldType":"String"},{"index":3,"width":15,"title":"库存量","fieldName":"stockAmount","fieldType":"Number"},{"index":4,"width":15,"title":"毛重","fieldName":"grossWeight","fieldType":"Number"},{"index":5,"width":10,"title":"物品类别","fieldName":"goodsType","fieldType":"String"},{"index":6,"width":15,"title":"规格型号","fieldName":"specs","fieldType":"String"},{"index":7,"width":25,"title":"单据号","fieldName":"docNo","fieldType":"String"},{"index":8,"width":10,"title":"客户名","fieldName":"customerName","fieldType":"String"},{"index":9,"width":15,"title":"备注","fieldName":"remark","fieldType":"String"},{"index":10,"width":10,"title":"来源","fieldName":"sourceType","fieldType":"String"},{"index":11,"width":22,"title":"创建时间","fieldName":"createTime","fieldType":"String","pattern":"yyyy-MM-dd HH:mm:ss"}]}]}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值