前言
優化springboot+poi導出excel表格,支持中文自適應的工具類.
工具類
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
public class ExportEncodeUtil {
public static void HeaderCode(HttpServletRequest request, HttpServletResponse response, String sheetName, HSSFWorkbook wb) throws IOException {
// 針對IE或者以IE爲內核的瀏覽器:
String userAgent = request.getHeader("User-Agent").toLowerCase();
String fileName = sheetName + ".xlsx";
if (userAgent.contains("msie") || userAgent.contains("trident")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// 非IE瀏覽器的處理:
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("success", "true");
OutputStream os = response.getOutputStream();
response.setHeader("Content-disposition", "attachment;filename=" + fileName);//默認Excel名稱
wb.write(os);
os.flush();
os.close();
}
/**
* 自適應寬度(中文支持)
* @param sheet
* @param size
*/
public static void setSizeColumn(HSSFSheet sheet, int size) {
for (int columnNum = 0; columnNum < size; columnNum++) {
int columnWidth = sheet.getColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
HSSFRow currentRow;
//當前行未被使用過
if (sheet.getRow(rowNum) == null) {
currentRow = sheet.createRow(rowNum);
} else {
currentRow = sheet.getRow(rowNum);
}
if (currentRow.getCell(columnNum) != null) {
HSSFCell currentCell = currentRow.getCell(columnNum);
if (currentCell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
int length = currentCell.getStringCellValue().getBytes().length;
if (columnWidth < length) {
columnWidth = length;
}
}
}
}
sheet.setColumnWidth(columnNum, columnWidth * 256);
}
}
}
service層關鍵代碼
/**
* 導出excel表格
* get方法
* @param request
* @param response
* @return
* @throws Exception
*/
public String export(HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Company> companies = companyRepository.findAll();
HSSFWorkbook wb = new HSSFWorkbook();//創建Excel文件
HSSFSheet sheet = wb.createSheet("企業信息表");
String sheetName = sheet.getSheetName();
wb.setSheetName(0, sheetName);
sheet.setDefaultRowHeight((short) (20 * 20));
CellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontHeightInPoints((short) 12);
style.setFont(font);
HSSFRow row = sheet.createRow(0);
row.createCell(0).setCellValue("企業名稱");//爲第一個單元格設值
row.createCell(1).setCellValue("社會信用代碼");//爲第二個單元格設值
row.createCell(2).setCellValue("聯繫人");//爲第三個單元格設值
row.createCell(3).setCellValue("聯繫電話");//爲第三個單元格設值
row.createCell(4).setCellValue("法人");//爲第三個單元格設值
row.createCell(5).setCellValue("地址");
row.createCell(6).setCellValue("行業");
row.createCell(7).setCellValue("創建日期");
row.createCell(8).setCellValue("開業日期");
row.createCell(9).setCellValue("員工數");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
if (companies != null && companies.size() > 0) {
int i = 0;
for (Company company : companies) {
i++;
row = sheet.createRow(i);
row.createCell(0).setCellValue(company.getName());
row.createCell(1).setCellValue(company.getCreditCode());
row.createCell(2).setCellValue(company.getContactName());
row.createCell(3).setCellValue(company.getContactPhone());
row.createCell(4).setCellValue(company.getCorporation());
row.createCell(5).setCellValue(company.getAddress());
row.createCell(6).setCellValue(company.getIndustryName());
String establishedDate = company.getEstablishedDate() != null ? sdf.format(company.getEstablishedDate()) : "";
row.createCell(7).setCellValue(establishedDate);
String openedDate = company.getOpenedDate() != null ? sdf.format(company.getOpenedDate()) : "";
row.createCell(8).setCellValue(openedDate);
Integer staffNum = company.getStaffNum() == null ? 0 : company.getStaffNum();
row.createCell(9).setCellValue(staffNum);
}
}
ExportEncodeUtil.setSizeColumn(sheet, companies .size());
ExportEncodeUtil.HeaderCode(request, response, sheetName, wb);
return "導出企業信息成功";
}