方便观看附上截图,具体代码在截图下方(当心跨域问题):
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ObjectUtils;
import net.sf.json.JSONArray;
public class ExcelUtil {
public static void exportExcel(HttpServletResponse response, String fileName, String[] titles,
List<Map<String, Object>> result) {
XSSFWorkbook wb = null;
OutputStream output = null;
try {
fileName = fileName + ".xlsx";
wb = new XSSFWorkbook();
XSSFSheet sh = wb.createSheet();
XSSFRow row = sh.createRow(0);
for (int i = 0; i < titles.length; i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(titles[i]);
}
JSONArray array = JSONArray.fromObject(result);
System.out.println(array);
for (int i = 1; i <= result.size(); i++) {
XSSFRow row1 = sh.createRow(i);
int j = 0;
Map<String, Object> map = result.get(i - 1);
for (Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
System.out.println(key);
XSSFCell cell = row1.createCell(j);
if (!ObjectUtils.isEmpty(entry.getValue())) {
cell.setCellValue(String.valueOf((entry.getValue())));
} else {
cell.setCellValue("");
}
j++;
}
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
try {
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
output = response.getOutputStream();
wb.write(output);
output.flush();
output.close();
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}