package com.gdz.excel.util;
import java.io.*;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javax.servlet.http.HttpServletResponse;
/**
* Excel导入导出
* @Author: guandezhi
* @Date: 2019/3/9 9:47
*/
public class ExcelUtil {
/**
* 导出多个sheet的excel
* @param name
* @param mapList
* @param response
* @param <T>
*/
public static <T> void exportMultisheetExcel(String name, List<Map> mapList, HttpServletResponse response) {
BufferedOutputStream bos = null;
try {
String fileName = name + ".xlsx";
bos = getBufferedOutputStream(fileName, response);
doExport(mapList, bos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 从excel中读内容
* @param filePath
* @param sheetIndex
* @return
*/
public static List<Map<String, String>> readExcel(String filePath, Integer sheetIndex) {
List<Map<String, String>> dataList = new ArrayList<>();
Workbook wb = ExcelUtil.createWorkBook(filePath);
if (wb != null) {
Sheet sheet = wb.getSheetAt(sheetIndex);
int maxRownum = sheet.getPhysicalNumberOfRows();
Row firstRow = sheet.getRow(0);
int maxColnum = firstRow.getPhysicalNumberOfCells();
String columns[] = new String[maxColnum];
for (int i = 0; i < maxRownum; i++) {
Map<String, String> map = null;
if (i > 0) {
map = new LinkedHashMap<>();
firstRow = sheet.getRow(i);
}
if (firstRow != null) {
String cellData = null;
for (int j = 0; j < maxColnum; j++) {
cellData = (String) ExcelUtil.getCellFormatValue(firstRow.getCell(j));
if (i == 0) {
columns[j] = cellData;
} else {
map.put(columns[j], cellData);
}
}
} else {
break;
}
if (i > 0) {
dataList.add(map);
}
}
}
return dataList;
}
private static BufferedOutputStream getBufferedOutputStream(String fileName, HttpServletResponse response) throws Exception {
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(fileName.getBytes("gb2312"