添加依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
代码
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUtils {
private static ExcelUtils instance = new ExcelUtils();
private ExcelUtils(){}
public static ExcelUtils getInstance(){
return instance;
}
public String createExcel(List<Map<String, Object>> mapList,String filename, String title) {
Map<String, Object> map = mapList.get(0);
Set<String> stringSet = map.keySet();
ArrayList<String> headList = new ArrayList<>(stringSet);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(title);
sheet.setDefaultRowHeight((short) (2 * 256));
for (int i = 0; i < headList.size(); i++) {
sheet.setColumnWidth(i, 8000);
}
XSSFFont font = wb.createFont();
font.setFontName("等线");
font.setFontHeightInPoints((short) 16);
XSSFRow titleRow = sheet.createRow(0);
XSSFCell titleCell = titleRow.createCell(0);
titleCell.setCellValue(title);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headList.size() - 1));
XSSFCellStyle cellStyle = wb.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.CENTER);
titleCell.setCellStyle(cellStyle);
XSSFRow row = sheet.createRow(1);
for (int i = 0; i < headList.size(); i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(headList.get(i));
}
XSSFRow rows;
XSSFCell cells;
for (int i = 0; i < mapList.size(); i++) {
rows = sheet.createRow(i + 2);
for (int j = 0; j < headList.size(); j++) {
String value = mapList.get(i).get(headList.get(j)).toString();
cells = rows.createCell(j);
cells.setCellValue(value);
}
}
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
String path = System.getProperty("user.dir") + "\\" + filename + dateFormat.format(date) + ".xlsx";
System.out.println("Excel文件输出路径: "+path);
try {
File file = new File(path);
FileOutputStream fileOutputStream = new FileOutputStream(file);
wb.write(fileOutputStream);
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
public static void main(String[] args) {
System.out.println("start...");
List<Map<String, Object>> mapArrayList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
Map<String, Object> map = new HashMap<>();
map.put("队列", i);
map.put("生产者", i);
map.put("消费者", i);
mapArrayList.add(map);
}
System.out.println("end...");
ExcelUtils.getInstance().createExcel(mapArrayList,"data","数据");
}
}