Last active
January 7, 2022 06:08
-
-
Save codethereforam/d75545684aae4cc0d4de126ef451ad32 to your computer and use it in GitHub Desktop.
基于easy POI的Excel导入/导出工具类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cn.afterturn.easypoi.excel.ExcelExportUtil; | |
import cn.afterturn.easypoi.excel.ExcelImportUtil; | |
import cn.afterturn.easypoi.excel.entity.ExportParams; | |
import cn.afterturn.easypoi.excel.entity.ImportParams; | |
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; | |
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult; | |
import lombok.extern.slf4j.Slf4j; | |
import org.apache.poi.ss.usermodel.Workbook; | |
import org.springframework.web.multipart.MultipartFile; | |
import javax.servlet.http.HttpServletResponse; | |
import java.io.OutputStream; | |
import java.util.List; | |
import java.util.Objects; | |
import java.util.function.Supplier; | |
/** | |
* Excel utility | |
* | |
* @author yanganyu | |
*/ | |
@Slf4j | |
public class ExcelUtil { | |
private ExcelUtil() { | |
throw new UnsupportedOperationException(); | |
} | |
/** | |
* 导出 | |
*/ | |
public static void doExport(Supplier<List<? extends BaseExportData>> exportedDataSupplier, String fileName, | |
Class<? extends BaseExportData> exportDataClass, HttpServletResponse response) { | |
List<? extends BaseExportData> exportedData = exportedDataSupplier.get(); | |
Objects.requireNonNull(exportedData); | |
ExportParams exportParams = new ExportParams(); | |
exportParams.setType(ExcelType.XSSF); | |
try (OutputStream output = response.getOutputStream(); | |
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, exportDataClass, exportedData)) { | |
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"), | |
"ISO8859-1")); | |
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); | |
workbook.write(output); | |
} catch (Exception e) { | |
log.error("导出[{}]失败", fileName); | |
} | |
} | |
/** | |
* 导入Excel | |
*/ | |
public static <D> ExcelImportResult<D> importFile(MultipartFile file, Class<? super D> clazz) { | |
String extName = FileUtil.extName(file.getOriginalFilename()); | |
if ("xls".equals(extName) || "xlsx".equals(extName)) { | |
try { | |
return ExcelImportUtil.importExcelMore(file.getInputStream(), clazz, new ImportParams()); | |
} catch (Exception e) { | |
throw new RuntimeException("读取excel文件报错", e); | |
} | |
} else { | |
throw new RuntimeException("只支持excel格式文件!"); | |
} | |
} | |
} | |
public abstract class BaseExportData { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment