localizer
ljw 2025-10-13 11:10:17 +08:00
parent ae3c856b28
commit 3fc015d6d9
1 changed files with 14 additions and 14 deletions

View File

@ -68,17 +68,17 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
SXSSFSheet sheet = (SXSSFSheet) writer.getSheet();
// 手动设置列宽,确保标题和数据内容都能完整显示
int columnCount = sheet.getRow(0).getLastCellNum();
/*int columnCount = sheet.getRow(0).getLastCellNum();
for (int i = 0; i < columnCount; i++) {
String headerText = "";
int maxContentLength = 0;
try {
// 获取标题文本
if (sheet.getRow(0) != null && sheet.getRow(0).getCell(i) != null) {
headerText = sheet.getRow(0).getCell(i).getStringCellValue();
}
// 遍历所有数据行,找到最长的内容
for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
if (sheet.getRow(rowIndex) != null && sheet.getRow(rowIndex).getCell(i) != null) {
@ -91,33 +91,33 @@ public class FileUtil extends cn.hutool.core.io.FileUtil {
} catch (Exception e) {
// 忽略获取单元格值的异常
}
// 根据标题和内容的最大长度计算合适的列宽
int headerLength = headerText.length();
int contentLength = maxContentLength;
int maxLength = Math.max(headerLength, contentLength);
// 设置列宽每个字符约2个字符宽度最小8个字符最大50个字符
int calculatedWidth = Math.max(Math.min(maxLength * 2, 50), 8) * 256;
int currentWidth = sheet.getColumnWidth(i);
// 设置列宽,确保标题和内容都能完整显示
sheet.setColumnWidth(i, Math.max(calculatedWidth, currentWidth));
}
}*/
// 尝试自动调整列宽
// try {
// sheet.trackAllColumnsForAutoSizing();
// writer.autoSizeColumnAll();
// } catch (Exception e) {
// log.warn("自动调整列宽失败,使用手动设置的列宽", e);
// }
try {
sheet.trackAllColumnsForAutoSizing();
writer.autoSizeColumnAll();
} catch (Exception e) {
log.warn("自动调整列宽失败,使用手动设置的列宽", e);
}
//response为HttpServletResponse对象
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
//设置文件名,支持中文文件名
try {
String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName + ";filename*=UTF-8''" + encodedFileName);
response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
} catch (Exception e) {
// 如果编码失败,使用默认文件名
response.setHeader("Content-Disposition", "attachment;filename=file.xlsx");