1. Excel 依赖包 POI
1.1 Maven 配置
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.7</version>
</dependency>
1.2 资源下载
Apache POI 官方下载
2. Java 代码示例
2.1 Excel 工具类
package com.mk.util;
import com.mk.bean.LogInfo;
import org.apache.poi.hssf.usermodel.*;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.util.CellRangeAddress;
public class Excels {
public static byte[] export(String sheetName, String title, List<LogInfo> list, int start, int end) {
if (list == null || start > end) {
return null;
}
();
initWorkbook(workbook, sheetName, title, list, start, end);
();
{
workbook.write(os);
[] bytes = os.toByteArray();
bytes;
} (IOException ex) {
Logger.getLogger(Excels.class.getName()).log(Level.SEVERE, , ex);
} {
{
os.close();
} (IOException ex) {
Logger.getLogger(Excels.class.getName()).log(Level.SEVERE, , ex);
}
}
;
}
;
{
end - start <= MAX_ROWS - ;
workbook.createSheet(sheetName);
initTitle(workbook, sheet, title, , , , , , , );
createStyle(workbook, , , HSSFFont.BOLDWEIGHT_BOLD);
createStyle(workbook, , , HSSFFont.BOLDWEIGHT_NORMAL);
sheet.createRow();
;
sheet.setColumnWidth(, baseFont * );
sheet.setColumnWidth(, baseFont * );
sheet.setColumnWidth(, baseFont * );
attrRow.createCell();
cell.setCellValue();
cell.setCellStyle(attrCellStyle);
cell = attrRow.createCell();
cell.setCellValue();
cell.setCellStyle(attrCellStyle);
cell = attrRow.createCell();
cell.setCellValue();
cell.setCellStyle(attrCellStyle);
();
( ; start < end; i++) {
list.get(start++);
sheet.createRow(i);
cell = row.createCell();
cell.setCellValue(logInfo.getIndex());
cell.setCellStyle(defaultCellStyle);
cell = row.createCell();
cell.setCellValue(dateFomater.format(logInfo.getTime()));
cell.setCellStyle(defaultCellStyle);
cell = row.createCell();
cell.setCellValue(logInfo.getInfo());
cell.setCellStyle(defaultCellStyle);
}
}
{
createStyle(workbook, fontSize, , HSSFFont.BOLDWEIGHT_BOLD);
sheet.createRow();
titleRow.setHeight(() height);
titleRow.createCell(rowIndex);
titleCell.setCellValue(title);
titleCell.setCellStyle(titleCellStyle);
sheet.addMergedRegion( (firstRow, lastRow, firstCol, lastCol));
}
HSSFCellStyle {
workbook.createFont();
font.setFontHeightInPoints(() fontSize);
font.setBoldweight(boldweight);
workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
cellStyle.setWrapText(wrapText);
cellStyle.setFont(font);
cellStyle;
}
}