package *;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* @ClassName ExportExcelUtils
* @Description TODO
* @DATE 2021/6/3 17:47
* @Version 1.0
*/
public class ExportExcelUtils {
/**
* 导出Excel文件模板
*
* @param sourceTableName 表名
* @param headList 表头
* @param response response
*/
public static void export (String sourceTableName, List<String> headList, HttpServletResponse response) {
sourceTableName = sourceTableName + "导入模板";
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFFont createFont = workbook.createFont();
// 设置字体
createFont.setFontHeightInPoints((short) 12);
XSSFCellStyle cellStyle = workbook.createCellStyle();
// 内容居左
cellStyle.setAlignment(HorizontalAlignment.LEFT);
cellStyle.setFont(createFont);
XSSFCellStyle cellStyle1 = workbook.createCellStyle();
// 水平居中
cellStyle1.setAlignment(HorizontalAlignment.CENTER);
cellStyle1.setFont(createFont);
//上下居中
cellStyle1.setVerticalAlignment(VerticalAlignment.CENTER);
XSSFSheet sheet = workbook.createSheet(sourceTableName);
XSSFRow row0 = sheet.createRow(0);
//起始行,终止行,起始列,终止列 3 9
for (int i = 0; i < headList.size(); i++) {
XSSFCell title = row0.createCell(i);
row0.createCell(i).setCellValue(headList.get(i));
sheet.setColumnWidth(i, 5000);
title.setCellStyle(cellStyle1);
}
ServletOutputStream fileOut = null;
try {
fileOut = response.getOutputStream();
String fileName = new String(sourceTableName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
fileOut = response.getOutputStream();
workbook.write(fileOut);
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
java导出自定义Excel文件头
最新推荐文章于 2025-04-21 15:22:19 发布