package org.springblade.common.utils;

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * Created By lidexi in 2021/6/30
 **/
public class Excelutil {
	/**
	 * 导出 Excel ：一个 sheet，带表头
	 *
	 * @param response HttpServletResponse
	 * @param list 数据 list，每个元素为一个 BaseRowModel
	 * @param fileName 导出的文件名

	 */
	public static void writeExcel(HttpServletResponse response, List<? extends BaseRowModel> list,
								  String fileName, WriteSheet sheet)throws Exception  {
		ExcelWriter writer = new ExcelWriter(getOutputStream(fileName, response), ExcelTypeEnum.XLSX);

		writer.write(list, sheet);
		writer.finish();
	}
	/**
	 * 导出文件时为Writer生成OutputStream
	 *
	 * @param fileName
	 * @param response
	 * @return
	 */
	public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
		//创建本地文件
		String filePath = fileName ;
		File dbfFile = new File(filePath);
		OutputStream outputStream = null;
		try {
			if (!dbfFile.exists() || dbfFile.isDirectory()) {
				dbfFile.createNewFile();
			}
			fileName = new String(filePath.getBytes(), "ISO-8859-1");
			response.addHeader("Content-Disposition", "filename=" + fileName);
			outputStream = response.getOutputStream();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (dbfFile.exists()) {
				dbfFile.delete();
			}
		}
		return outputStream;
	}
}
