一、pom依赖
3.10-FINAL
org.apache.poi
poi
${org.apache.poi.version}
org.apache.poi
poi-ooxml
${org.apache.poi.version}
org.apache.poi
poi-ooxml-schemas
${org.apache.poi.version}
二、封装的服务
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tf56.hermescontractweb.util.DateUtil;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
@Slf4j
@Service
public class ExcelExportService {
@Autowired
private HermesFileService hermesFileService;
/**
* 导出excel
* @param excelDataList:需要导出的数据 List
* @param clazz 对应excelDataList具体类型的clazz(导出excel表头使用javaBean属性名)
* @param response
* @throws Exception
*/
public void exportExcel2003(List excelDataList, Class clazz, HttpServletResponse response) throws Exception {
List excelTitles = getExcelTitles(clazz);
List
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateUtil {
public static String datetime = "yyyy-MM-dd HH:mm:ss";
public static String date_format = "yyyy-MM-dd";
/**
* 获取当前时间
*/
public static String getCurrentDateTime() {
SimpleDateFormat sdf = getDateFormat(datetime);
return sdf.format(new Date());
}
public static String getDateTime(Date date) {
if (date == null) {
return "";
}
SimpleDateFormat sdf = getDateFormat(datetime);
return sdf.format(date);
}
public static String getDate(Date date) {
if (date == null) {
return "";
}
SimpleDateFormat sdf = getDateFormat(date_format);
return sdf.format(date);
}
private static SimpleDateFormat getDateFormat(String parttern) throws RuntimeException {
return new SimpleDateFormat(parttern);
}
}
三、调用示例
public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
// 获取需要导出的数据列表 需是javaBean的一个数据列表
List exportJavaBeans = xxxx;
// 导出excel2003
excelExportService.exportExcel2003(exportJavaBeans, ExportJavaBean.class, response);
// 导出excel2007
excelExportService.exportExcel2007(exportJavaBeans, ExportJavaBean.class, response);
}
四、此种导出excel缺点
若存在Date类型的数据,会按Long类型格式当做数字输出