第一步:导入依赖
<!--数据导出依赖 excel-->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<!--数据导出依赖 End excel-->
第二步:复制我的这两个类到项目中
package com.asiainfo.utils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;
/**
*
* @ClassName: ExcelUtil
* @Description: Excel工具类
* @author huangxh
* @date 2016年10月19日
*
*/
public class ExcelUtil {
public static final String CONTEXTPATH = "dqam\\";
public static final String XLSX = ".xlsx";
/**
* 获取导出excel的路径和文件名
*
* @param request
* @param fileName
* @return
*/
public static String getExportExcelFilePath(HttpServletRequest request,
String fileName) {
if ("".equals(fileName) || fileName == null) {
return "";
} else {
return request.getSession().getServletContext().getRealPath("/")
+ CONTEXTPATH + fileName
+ XLSX;
}
}
/**
* 创建XSSFWorkbook
*
* @param filePath
* @return
* @throws IOException
*/
public static XSSFWorkbook getXSSFWorkbook(File file, String filePath)
throws IOException {
XSSFWorkbook workbook = null;
if (!file.exists()) {
workbook = new XSSFWorkbook();
} else {
workbook = new XSSFWorkbook(filePath);
}
return workbook;
}
/**
* 保存Excel 2003报表到指定目录
*
* @param path
* 指定保存目录
* @param book
* 报表文件
* @param fileName
* 报表名称
* @throws IOException
*/
public static void saveExcel2003ToTargetPath(String path,
HSSFWorkbook book, String fileName) throws IOException {
File file = new File(path + fileName);
OutputStream out = new FileOutputStream(file);
book.write(out);
out.flush();
out.close();
}
/**
* 保存Excel 2003报表到指定目录
*
* @param path
* 指定保存目录
* @param book
* 报表文件
* @param fileName
* 报表名称
* @throws IOException
*/
public static void saveExcel2007ToTargetPath(String path,
XSSFWorkbook book, String fileName) throws IOException {
File file = new File(path + "/" + fileName);
OutputStream out = new FileOutputStream(file);
book.write(out);
out.flush();
out.close();
}
/**
*
* 动态组装Excel 2003 Sheet
*
* @param book
* Excel报表对象
* @param dataSet
* 报表数据,不包含表头
* @param header
* 报表表头
* @param sheetName
* sheet名称
*/
public static void saveSheet2003DataToExcel(HSSFWorkbook book,
List<HashMap<String, Object>> dataSet, String[] header,
String sheetName) {
if (header == null || header.length <= 0) {
return;
}
HSSFSheet sheet = book.createSheet(sheetName);
Map<String, HSSFCellStyle> styleMap = getMyHssFcellStyle(book);
HSSFRow titlerow = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
HSSFCell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
cell.setCellStyle(styleMap.get("defaultStyle"));// 设置样式
// 添加表头样式
}
if (dataSet == null || dataSet.isEmpty()) {
return;
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Map<String, Object> datamap = dataSet.get(i);
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
HSSFCell cell = row.createCell(j);
cell.setCellValue(String.valueOf(datamap.get(header[j])));
// 添加单元格表样式
}
}
for (int i = 0; i < header.length; i++) {
sheet.setColumnWidth(i, 5500);// 宽
}
}
/**
* 保存数据到Excel 2003,并存放到指定目录,包含数字格式化千分符 2015年1月12日10:05:20 在原有基础上添加默认方式
*
* @param dataSet
* 报表数据,不包含表头
* @param header
* 报表表头
*/
public static void saveToExcelFX(HSSFWorkbook book,
List<HashMap<String, Object>> dataSet, String[] header,
String sheetName, String styleType) {
if (header == null || header.length <= 0) {
return;
}
HSSFSheet sheet = book.createSheet(sheetName);
HSSFRow titlerow = sheet.createRow(0);
Map<String, HSSFCellStyle> styleMap = getMyHssFcellStyle(book);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
HSSFCell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
// 添加表头样式
cell.setCellStyle(styleMap.get("defaultStyle"));
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Map<String, Object> datamap = dataSet.get(i);
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
HSSFCell cell = row.createCell(j);
if (datamap.get(header[j]) != null) {
String value = String.valueOf(datamap.get(header[j]));
// 2015年1月12日10:04:52 xizf
// 添加,如果传入默认模式,则所有字段均按普通方式处理,不区分数据等数据要求
if ("default".equalsIgnoreCase(styleType)) {
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("defaultStyle"));
} else {
if (isNumberic(value) && j > 0
&& StringUtil.stringHasValue(value)) {
if (isNum(value)) {
cell.setCellValue(Double.parseDouble(value));
cell.setCellStyle(styleMap.get("numStyle"));
} else {
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("feeStyle"));
}
} else {
if (value.contains("%")) {
try {
cell.setCellValue(Double.parseDouble(value
.replace("%", "")) + "%");
cell.setCellStyle(styleMap.get("numStyle"));
} catch (Exception e) {
if (value.contains(",")) {
// 超过1000%又对之前的数据格式化了的字符串型百分数,比如1,000%需要这样处理。
cell.setCellValue(value);
cell.setCellStyle(styleMap
.get("defaultStyle"));
} else {
cell.setCellValue(Double
.parseDouble("0"));
cell.setCellStyle(styleMap
.get("percentStyle"));
}
}
} else {
value = value.replaceAll("--", " --");
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
}
} else {
cell.setCellValue(" --");
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
}
for (int i = 0; i < header.length; i++) {
sheet.setColumnWidth(i, 5500);// 宽
}
}
/**
* 保存数据到Excel 2003,并存放到指定目录,包含数字格式化千分符
*
* @param dataSet
* 报表数据,不包含表头
* @param header
* 报表表头
*/
public static void saveToExcel(HSSFWorkbook book,
List<HashMap<String, Object>> dataSet, String[] header,
String sheetName) {
if (header == null || header.length <= 0) {
return;
}
HSSFSheet sheet = book.createSheet(sheetName);
HSSFRow titlerow = sheet.createRow(0);
Map<String, HSSFCellStyle> styleMap = getMyHssFcellStyle(book);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
HSSFCell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
// 添加表头样式
cell.setCellStyle(styleMap.get("defaultStyle"));
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Map<String, Object> datamap = dataSet.get(i);
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
HSSFCell cell = row.createCell(j);
if (datamap.get(header[j]) != null) {
String value = String.valueOf(datamap.get(header[j]));
if (isNumberic(value) && j > 0
&& StringUtil.stringHasValue(value)) {
if (isNum(value)) {
cell.setCellValue(Double.parseDouble(value));
cell.setCellStyle(styleMap.get("numStyle"));
} else {
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("feeStyle"));
}
} else {
if (value.contains("%")) {
try {
cell.setCellValue(Double.parseDouble(value
.replace("%", "")) + "%");
cell.setCellStyle(styleMap.get("numStyle"));
} catch (Exception e) {
if (value.contains(",")) {
// 超过1000%又对之前的数据格式化了的字符串型百分数,比如1,000%需要这样处理。
cell.setCellValue(value);
cell.setCellStyle(styleMap
.get("defaultStyle"));
} else {
cell.setCellValue(Double.parseDouble("0"));
cell.setCellStyle(styleMap
.get("percentStyle"));
}
}
} else {
value = value.replaceAll("--", " --");
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
} else {
cell.setCellValue(" --");
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
}
for (int i = 0; i < header.length; i++) {
sheet.setColumnWidth(i, 5500);// 宽
}
}
public static void saveToExcel2(HSSFWorkbook book,
List<Map<String, Object>> dataSet, String[] header,
String sheetName) {
if (header == null || header.length <= 0) {
return;
}
HSSFSheet sheet = book.createSheet(sheetName);
HSSFRow titlerow = sheet.createRow(0);
Map<String, HSSFCellStyle> styleMap = getMyHssFcellStyle(book);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
HSSFCell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
HSSFFont font = book.createFont();// 生成一个字体样式
font.setFontHeight((short) 250); //字体大小
HSSFCellStyle style=book.createCellStyle();
style.setFont(font);
cell.setCellStyle(style);
// 添加表头样式
//cell.setCellStyle(styleMap.get("defaultStyle"));
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Map<String, Object> datamap = dataSet.get(i);
HSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
HSSFCell cell = row.createCell(j);
if (datamap.get(header[j]) != null) {
String value = String.valueOf(datamap.get(header[j]));
if (isNumberic(value) && j > 0
&& StringUtil.stringHasValue(value)) {
if (isNum(value)) {
cell.setCellValue(Double.parseDouble(value));
cell.setCellStyle(styleMap.get("defaultStyle"));
} else {
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("feeStyle"));
}
} else {
if (value.contains("%")) {
try {
cell.setCellValue(Double.parseDouble(value
.replace("%", "")) + "%");
cell.setCellStyle(styleMap.get("numStyle"));
} catch (Exception e) {
if (value.contains(",")) {
// 超过1000%又对之前的数据格式化了的字符串型百分数,比如1,000%需要这样处理。
cell.setCellValue(value);
cell.setCellStyle(styleMap
.get("defaultStyle"));
} else {
cell.setCellValue(Double.parseDouble("0"));
cell.setCellStyle(styleMap
.get("percentStyle"));
}
}
} else {
value = value.replaceAll("--", " --");
cell.setCellValue(value);
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
} else {
cell.setCellValue(" --");
cell.setCellStyle(styleMap.get("defaultStyle"));
}
}
}
for (int i = 0; i < header.length; i++) {
sheet.setColumnWidth(i, 5500);// 宽
}
}
/**
* 导出大数据量excel文件
*
* @param list
* @param reportTitle
* @throws IOException
*/
public static void saveToExcelSXSS(List list, String sheetName,
String reportTitle, SXSSFWorkbook book) throws IOException {
if (reportTitle == null || reportTitle.length() <= 0) {
return;
}
String[] header = null;
header = reportTitle.split(",");
List<String[]> recordList = new ArrayList<String[]>();
Sheet sheet = book.createSheet(sheetName);
Row titlerow = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
Cell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
sheet.setColumnWidth(i, 5000);
}
List dataSet = list;
if (dataSet == null || dataSet.isEmpty()) {
return;
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Object[] datamap = (Object[]) dataSet.get(i);
Row row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
Cell cell = row.createCell(j);
cell.setCellValue(String.valueOf(datamap[j]));
}
}
}
/**
* 获取Excel样式
*
* @param book
* @return
*/
public static Map<String, HSSFCellStyle> getMyHssFcellStyle(
HSSFWorkbook book) {
Map<String, HSSFCellStyle> styleMap = new HashMap<String, HSSFCellStyle>();
return styleMap;
}
/**
* 设置Excel样式
*
* @param book
* @return
*/
public static HSSFCellStyle getHssFcellStyle(HSSFWorkbook book) {
HSSFCellStyle cellStyle = book.createCellStyle();
cellStyle.setTopBorderColor(HSSFColor.BLACK.index);
cellStyle.setWrapText(true);
return cellStyle;
}
public static boolean isNumberic(String str) {
if (str == null) {
return false;
}
if (str.split("\\.").length > 2){
return false;}
if (str.split("-").length > 2){
return false;}
str = str.replace(".", "").replaceAll("-", "");
if (str.equals("") || str.length() == 0) {
return false;
}
int sz = str.length();
for (int i = 0; i < sz; i++) {
if (Character.isDigit(str.charAt(i)) == false) {
return false;
}
}
return true;
}
// 判断是否为整型数字
public static boolean isNum(String s) {
if (s.contains(".") || s.indexOf("-") > 0) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println("-2.0".split("-").length);
}
/**
*
* 动态组装Excel 2007/2010 Sheet
*
* @param book
* Excel报表对象
* @param dataSet
* 报表数据,不包含表头
* @param header
* 报表表头
* @param sheetName
* sheet名称
*/
public static void saveSheet2010DataToExcel(XSSFWorkbook book,
List<HashMap<String, Object>> dataSet, String[] header,
String sheetName) {
if (dataSet == null || dataSet.isEmpty() || header == null
|| header.length <= 0) {
return;
}
XSSFSheet sheet = book.createSheet(sheetName);
XSSFRow titlerow = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
// 创建Sheet头
XSSFCell cell = titlerow.createCell(i);
cell.setCellValue(header[i]);
// 添加表头样式
}
for (int i = 0; i < dataSet.size(); i++) {
// 插入Sheet数据
Map<String, Object> datamap = dataSet.get(i);
XSSFRow row = sheet.createRow(i + 1);
for (int j = 0; j < header.length; j++) {
// 创建Sheet头
XSSFCell cell = row.createCell(j);
cell.setCellValue(String.valueOf(datamap.get(header[j])));
// 添加单元格表样式
}
}
}
/**
* 通过递归,查找最后一个last Row Number 的下标,(而不是长度)
*
* @param hsheet
* exce12003 sheet
* @param xsheet
* exce12007 sheet
* @param num
* row.lastRowNum() 最后一个row
* @param columnIdSet
* 要查询cell 的下标
* @return
*/
public static int getLastRowByfirstCell(HSSFSheet hsheet, XSSFSheet xsheet,
int num, Set<Integer> columnIdSet) {
if (num <= 0){
return num;}
boolean falg = false;
if (xsheet != null)// excel 2007
{
XSSFRow row = xsheet.getRow(num);
if (row == null) {
return getLastRowByfirstCell(null, xsheet, num - 1, columnIdSet);
} else {
for (Integer columnId : columnIdSet) {
if (row.getCell(columnId) != null
&& !"".equals(row.getCell(columnId).toString()
.trim())) {
falg = true;
break;
}
}
if (!falg) {
return getLastRowByfirstCell(null, xsheet, num - 1,
columnIdSet);
}
return num;
}
} else // excel 2003
{
HSSFRow row = hsheet.getRow(num);
if (row == null) {
return getLastRowByfirstCell(hsheet, null, num - 1, columnIdSet);
} else {
for (Integer columnId : columnIdSet) {
if (row.getCell(columnId) != null
&& !"".equals(row.getCell(columnId).toString()
.trim())) {
falg = true;
break;
}
}
if (!falg) {
return getLastRowByfirstCell(hsheet, null, num - 1,
columnIdSet);
}
return num;
}
}
}
/**
* 创建Excel 默认样式
*/
public static void createDefaultSheetStyles() {
}
/**
* 将1~25*26间的整数转化为excel列名,比如27转为AA等
* @param intNumber
* @throws Exception
*/
public static String TransColIndexIntToStr(int intNumber) throws Exception {
if (intNumber < 1){
intNumber = 1;}
if (intNumber > (25 * 26)){
intNumber = 25 * 26;}
int i = intNumber;
char[] digits = {
'Z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y' };
char buf[] = new char[27];
boolean negative = (i < 0);
int charPos = 26;
if (!negative) {
i = -i;
}
while (i <= -26) {
buf[charPos--] = digits[-(i % 26)];
i = i / 26;
}
buf[charPos] = digits[-i];
if (negative) {
buf[--charPos] = '-';
}
String result = new String(buf, charPos, (27 - charPos));
if (result.indexOf('Z') != -1) {
if (result.charAt(0) == 'A') {
result = "Z";
} else {
result = (char) (result.charAt(0) - 1) + "Z";
}
}
return result;
}
}
package com.asiainfo.utils;
/**
* @author shurong
* @Date 2020/11/3 14:18
* 字符串工具
*/
public class StringUtil {
/**
* 判断字符串是否为空
*
* @param str
* @return boolean
*
*/
public static boolean isEmpty(Object str) {
return (str == null || (String.valueOf(str)).trim().length() < 1);
}
public static boolean stringHasValue(String s) {
return s != null && s.length() > 0;
}
}
第三步:复制下列代码到Controller层
这里要注意了
- headStr是你要设置的表头
- list是你从数据库里查出来的数据结果集
- 下面这个核心代码块是你设置excel表每一列与java数据之间的对应关系
if(list.size()!=0)
{
for(int i=0;i<list.size();i++)
{
HashMap<String, Object> hmap = new HashMap<String, Object>();
hmap.put(headStr[0],list.get(i).getOrderId());
hmap.put(headStr[1],list.get(i).getTsnr());
hmap.put(headStr[2],list.get(i).getClsm());
resultList.add(hmap);
}
}
@RequestMapping(value = "aiComplaintMange/exportOrderDetail",method = RequestMethod.GET)
public void exportExcel(@RequestParam Map<String,String> paramMap, HttpServletResponse response)
{
List<Order>list=new ArrayList<>();
String[] headStr = {
"编号", "投诉内容", "解决措施" };
List resultList=new ArrayList();
Map resultMap=new HashMap();
String sheetName = "";
String code="200";
try{
String type = paramMap.get("dateType");
String navDesc = paramMap.get("currentTaskId");
String resDep = paramMap.get("resDep");
String channel = paramMap.get("classType");
String orderType = paramMap.get("orderType");
String setDate = Integer.parseInt(paramMap.get("date").split("-")[0]) + "/" + Integer.parseInt(paramMap.get("date").split("-")[1]) + "/" + Integer.parseInt(paramMap.get("date").split("-")[2]);
String searchValue = paramMap.get("search");
if ("导航节点".equals(orderType)) {
navDesc = searchValue;
searchValue = "";
}
if ("year".equals(type)){
setDate = setDate.split("/")[0];
}
if ("year".equals(type) || "day".equals(type) || "week".equals(type)){
list = orderService.getOrderList(setDate,1,999999,searchValue,navDesc,resDep,channel,type);
}
if ("month".equals(type)){
list = orderService.getOrderListByMonth(setDate,1,999999,searchValue,navDesc,resDep,channel);
}
if(list.size()!=0)
{
for(int i=0;i<list.size();i++)
{
HashMap<String, Object> hmap = new HashMap<String, Object>();
hmap.put(headStr[0],list.get(i).getOrderId());
hmap.put(headStr[1],list.get(i).getTsnr());
hmap.put(headStr[2],list.get(i).getClsm());
resultList.add(hmap);
}
}
sheetName="投诉工单详情表";
exportExcelBase(resultList, headStr, sheetName, response);
resultMap.put("code",code);
}
catch (Exception e)
{
code="400";
e.printStackTrace();
}
resultMap.put("code",code);
}
protected void exportExcelBase(List<HashMap<String, Object>> hashMapList,
String[] headStr, String sheetName, HttpServletResponse response) {
HSSFWorkbook book = new HSSFWorkbook();
com.asiainfo.utils.ExcelUtil.saveToExcel(book, hashMapList, headStr, sheetName);
String fileName = sheetName + ".xls";
OutputStream myout = null;
try {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="
+ fileName);
try {
myout = response.getOutputStream();
book.write(myout);
} catch (IOException e) {
}
} finally {
try {
myout.flush();
myout.close();
} catch (IOException e) {
}
}
}