Java代码
package com.util;
import org.apache.poi.hssf.usermodel.*;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;
public class ExportExcel {
public static HSSFCell getCell(HSSFSheet sheet, int row, int col) {
HSSFRow sheetRow = sheet.getRow(row);
if (sheetRow == null) {
sheetRow = sheet.createRow(row);
}
HSSFCell cell = sheetRow.getCell(col);
if (cell == null) {
cell = sheetRow.createCell(col);
}
return cell;
}
public static void setText(HSSFCell cell, String text) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
}
public static void toExcel(List<String> titles, List<Map> list) throws Exception {
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("第一个Sheet页");
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
for (int i = 0; i < titles.size(); i++) {
String title = titles.get(i);
cell = getCell(sheet, 0, i);
setText(cell, title);
cell.setCellStyle(style);
}
for (int i = 0; i < list.size(); i++) {
Map item = list.get(i);
for (int j = 0; j < titles.size(); j++) {
String varstr = "";
if (j == 0) {
varstr = item.get("url") != null ? item.get("url").toString() : "";
} else if (j == 1) {
varstr = item.get("moduleName") != null ? item.get("moduleName").toString() : "";
} else if (j == 2) {
varstr = item.get("sum") != null ? item.get("sum").toString() : "";
}
cell = getCell(sheet, i + 1, j);
setText(cell, varstr);
cell.setCellStyle(style);
}
}
FileOutputStream fileOut = new FileOutputStream("F://日志.xls");
wb.write(fileOut);
fileOut.close();
}
}
public static void main(String argv[])throws Exception {
List<Map> list = new ArrayList();
Map map1=new HashMap();
map1.put("url","https://www.baidu.com/");
map1.put("moduleName","百度");
map1.put("sum","5");
list.add(map1);
Map map2=new HashMap();
map2.put("url","http://www.google.cn/");
map2.put("moduleName","谷歌");
map2.put("sum","8");
list.add(map2);
List<String> titleList = new ArrayList<>();
titleList.add("访问路径");
titleList.add("访问页面");
titleList.add("访问次数");
ExportExcel.toExcel(titleList,list);
}