import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
@Slf4j
public class ExcelUtils {
public static void exportExcel(HttpServletResponse response,
List<List<Object>> excelData,
String sheetName,
String fileName,
int columnWidth) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(sheetName);
sheet.setDefaultColumnWidth(columnWidth);
int rowIndex = 0;
for(List<Object> data : excelData){
HSSFRow row = sheet.createRow(rowIndex++);
for (int i = 0; i < data.size(); i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(data.get(i).toString());
cell.setCellValue(text);
}
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
workbook.write(response.getOutputStream());
workbook.close();
}
public static void downloadFile(HttpServletResponse response,String fileName) throws IOException {
String path = BusinessConstants.LINUXTEMPLATE;
File file = new File(path+fileName);
File fileParent = file.getParentFile();
if (!fileParent.exists()) {
throw new BusinessException(ResultCodeEnum.FILE_ERROR_EXISTS.getCode(),ResultCodeEnum.FILE_ERROR_EXISTS.getMsg(),ResultCodeEnum.FILE_ERROR_EXISTS.getMsgEn());
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.flushBuffer();
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
log.info(fileName + "下载成功!");
} catch (Exception e) {
log.info(fileName + "下载失败!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static <T> List<T> importExcel(MultipartFile file,Class<T> clz) throws IllegalAccessException, InstantiationException, NoSuchFieldException,IOException {
if(file == null || file.getSize() == 0){
throw new BusinessException(ResultCodeEnum.EXCEL_ERROR_IMPORT.getCode(),ResultCodeEnum.EXCEL_ERROR_IMPORT.getMsg(),ResultCodeEnum.EXCEL_ERROR_IMPORT.getMsgEn());
}
String fileName = file.getOriginalFilename();
InputStream inputStream = file.getInputStream();
if(!(fileName.endsWith(".xls") || fileName.endsWith(".xlsx"))){
throw new BusinessException(ResultCodeEnum.EXCEL_ERROR_IMPORT.getCode(),ResultCodeEnum.EXCEL_ERROR_IMPORT.getMsg(),ResultCodeEnum.EXCEL_ERROR_IMPORT.getMsgEn());
}else if(fileName.endsWith(".xls")){
log.info(fileName + ":开始解析转换");
return translateXls(inputStream,clz);
}else{
log.info(fileName + ":开始解析转换");
return translateXlsx(inputStream,clz);
}
}
private static <T> List<T> translateXls(InputStream inputStream,Class<T> clz) throws IllegalAccessException, InstantiationException, NoSuchFieldException, IOException {
List<T> list = new ArrayList<>();
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
HSSFSheet sheet = workbook.getSheetAt(0);
HSSFRow firstRow = sheet.getRow(0);
List<String> headerList = new ArrayList<>();
for (int i = 0; i < firstRow.getLastCellNum(); i++) {
headerList.add(firstRow.getCell(i).getStringCellValue());
}
for (int i = 1; i < sheet.getLastRowNum(); i++) {
HSSFRow row = sheet.getRow(i);
T t = (T)clz.newInstance();
for (int j = 0; j < headerList.size(); j++) {
Field field = clz.getDeclaredField(headerList.get(j));
field.setAccessible(true);
field.set(t, row.getCell(j).getStringCellValue());
}
list.add(t);
}
log.info("解析转换完成");
return list;
}
private static <T> List<T> translateXlsx(InputStream inputStream,Class<T> clz) throws IllegalAccessException, InstantiationException, NoSuchFieldException, IOException {
List<T> list = new ArrayList<>();
XSSFWorkbook workbook = new XSSFWorkbook (inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow firstRow = sheet.getRow(0);
List<String> headerList = new ArrayList<>();
for (int i = 0; i < firstRow.getLastCellNum(); i++) {
headerList.add(firstRow.getCell(i).getStringCellValue());
}
for (int i = 1; i < sheet.getLastRowNum(); i++) {
XSSFRow row = sheet.getRow(i);
T t = (T)clz.newInstance();
for (int j = 0; j < headerList.size(); j++) {
Field field = clz.getDeclaredField(headerList.get(j));
field.setAccessible(true);
field.set(t, row.getCell(j).getStringCellValue());
}
list.add(t);
}
log.info("解析转换完成");
return list;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了