引入pom
<!-- 操作Excel文件的poi包引入 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- poi-ooxml可以操作.xlsx 文件 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
java导入Excel数据
Controller层
@PostMapping(value = "/importInfo")
public Map<String, Object> importInfo(@CookieValue(value = "token_back") String token, @RequestParam(value = "file") MultipartFile file, @RequestParam(value = "code") String code) {
TbSysUser user = RedisUtil.tokenToUser(token);
String operatorId = user.getLoginCode();
String operatorName = user.getName();
Timestamp operateDateTime = new Timestamp(new Date().getTime());
Map<String, Object> map = new HashMap<>();
try {
String message = memberImportService.exportInfo(file, code, operatorId, operatorName, operateDateTime);
map.put("success", true);
map.put("message", message);
return map;
} catch (Exception e) {
e.printStackTrace();
map.put("success", false);
map.put("message", "导入失败");
return map;
}
}
ServiceImpl层
@Override
public String exportInfo(MultipartFile file, String code, String operatorId, String operatorName, Timestamp operateDateTime) throws Exception {
String message = "导入成功";
String listTypeID = code.split("\\*")[0].toString().trim();
String listTypeName = code.split("\\*")[1].toString().trim();
Workbook workbook = null;
String fileName = file.getOriginalFilename();
ExcelUtil eu = new ExcelUtil();
if (fileName.endsWith("xls")) {
try {
workbook = new HSSFWorkbook(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
} else if (fileName.endsWith("xlsx")) {
try {
workbook = new XSSFWorkbook(file.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
throw new Exception("文件不是Excel文件");
} catch (IOException e) {
e.printStackTrace();
}
}
Sheet sheet = workbook.getSheet("sheet1");
int rows = sheet.getLastRowNum();
if (rows == 0) {
try {
throw new Exception("数据为空请重新填写数据");
} catch (Exception e) {
e.printStackTrace();
}
}
Sheet sht0 = workbook.getSheetAt(0);
Row ro = sht0.getRow(1);
boolean flag = false;
Cell cell = ro.getCell(4);
String cellName = null;
if (cell != null) {
cellName = cell.getStringCellValue();
}
if (cellName != null && cellName.trim().length() > 0) {
if (!"备注".equals(cellName)) {
message = "导入模板错误,请重新导入";
return message;
}
flag = true;
} else {
cell = ro.getCell(2);
if (cell != null) {
cellName = cell.getStringCellValue();
}
if (cellName == null || (cellName.trim().length() > 0 && !"备注".equals(cellName))) {
message = "导入模板错误,请重新导入";
return message;
}
}
for (Row r : sht0) {
int rnum = r.getRowNum() + 1;
if (r.getRowNum() < 2) {
continue;
}
TbMemberImport info = new TbMemberImport();
info.setYear(eu.getCellValue(r.getCell(0)));
info.setFullName(eu.getCellValue(r.getCell(1)));
if (flag) {
String memo = eu.getCellValue(r.getCell(4));
if (memo != null && memo.trim().length() > 0) {
info.setMemo(eu.getCellValue(r.getCell(4)));
} else {
message = "第" + rnum + "行备注不能为空!";
return message;
}
info.setVarietyName(eu.getCellValue(r.getCell(2)));
info.setDayProcess(new java.math.BigDecimal(eu.getCellValue(r.getCell(3))));
} else {
String memo = eu.getCellValue(r.getCell(2));
if (memo != null && memo.trim().length() > 0) {
info.setMemo(eu.getCellValue(r.getCell(4)));
} else {
message = "第" + rnum + "行备注不能为空!";
return message;
}
}
info.setMemberId("");
info.setVarietyId("");
info.setOperatorId(operatorId);
info.setOperatorName(operatorName);
info.setOperateDateTime(operateDateTime);
info.setListTypeId(listTypeID);
info.setListTypeName(listTypeName);
info.setStatus("WX");
tbMemberImportMapper.insert(info);
for (int i = 1; i <= rows + 1; i++) {
Row row = sheet.getRow(i);
if (row != null) {
}
}
}
return message;
}
java 导出Excel
Controller层
@PostMapping("/export")
public void exportContractList(HttpServletRequest request, HttpServletResponse response, @CookieValue(value="token_back")String token){
try {
List<TbContractExport> contractList = contractMngService.contractExportData(request,RedisUtil.tokenToUser(token));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())+"合同信息", "UTF-8") + ".xls");
ExcelUtil<TbContractExport> excelUtil = new ExcelUtil<>();
excelUtil.exportExcel2003("合同信息", exportColumns, contractList, response.getOutputStream(), "yyyy-MM-dd");
}catch (Exception e){
}
}
@GetMapping(value = "/exportExcel")
public void exportExcel(
HttpServletResponse response,
@RequestParam(value = "data") String data
) {
try {
JSONObject jsonObject = JSONObject.parseObject(data);
String buyStatus = jsonObject.getString("buyStaus");
String fullName = jsonObject.getString("fullName");
String listTypeId = jsonObject.getString("listTypeId");
String marketId = jsonObject.getString("marketId");
String marketIdZc = jsonObject.getString("marketIdZc");
String memberId = jsonObject.getString("memberId");
String varietyId = jsonObject.getString("varietyId");
String status = jsonObject.getString("status");
String specialNo = jsonObject.getString("specialNo");
memberBuyNumLimitService.exportExcel(response, buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
} catch (Exception e) {
e.printStackTrace();
}
}
ServiceImpl层
@Override
public void exportExcel(HttpServletResponse response, String buyStatus, String fullName, String listTypeId, String marketId, String marketIdZc, String memberId, String varietyId, String status, String specialNo) throws Exception {
List<TbMemberBuyNumLimitView> list = null;
if (marketIdZc == null || marketIdZc.trim().length() <= 0) {
list = tbMemberBuyNumLimitMapper.getMemberBuyInfo(buyStatus, fullName, listTypeId, marketId, memberId, varietyId, status, specialNo);
} else {
list = tbMemberBuyNumLimitMapper.getMemberBuyInfoZc(buyStatus, fullName, listTypeId, marketId, marketIdZc, memberId, varietyId, status, specialNo);
}
ExcelUtil excelUtil = new ExcelUtil();
String[] headers = {"名单", "代码", "名称", "市场", "专场", "品种", "处理能力", "单次可交易量", "1可交易量", "2可交易量", "承诺书", "交易状态", "交易量限制"};
List<Object> rows = new ArrayList<>();
for (TbMemberBuyNumLimitView tb : list) {
List<String> row = new ArrayList<>();
String numConvertName = tb.getNumConvertName();
row.add(tb.getListTypeName());
row.add(tb.getMemberId());
row.add(tb.getFullName());
row.add(tb.getMarketName());
row.add(tb.getSpecialName());
row.add(tb.getVarietyName());
if(tb.getDayProcess() == null){
row.add("无数据");
}else{
row.add(tb.getDayProcess().toString() + numConvertName);
}
if(tb.getSingleBuy() == null){
row.add("无数据");
}else {
row.add(tb.getSingleBuy().toString() + numConvertName);
}
if(tb.getMonthBuy() == null){
row.add("无数据");
}else {
row.add(tb.getMonthBuy().toString() + numConvertName);
}
if(tb.getTotalBuy() == null){
row.add("无数据");
}else {
row.add(tb.getTotalBuy().toString() + numConvertName);
}
String commitment = tb.getCommitment();
if ("Y".equals(commitment)) {
row.add("是");
} else {
row.add("否");
}
String bs = tb.getBuyStatus();
if ("Y".equals(bs)) {
row.add("可交易");
} else {
row.add("停止交易");
}
String st = tb.getStatus();
if ("Y".equals(st)) {
row.add("限制");
} else {
row.add("不限制");
}
rows.add(row);
}
String time = DateUtils.dateToStringByTemplate(new Date(), "yyyyMMddHHmmss");
String fileName = time + "*****列表.xls";
excelUtil.listToExcel(headers, rows, fileName, "某某列表", response);
}
导出Excel工具
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ExcelUtil<T> {
public final static String EXCEL_FILE_2007 = "2007";
public final static String EXCEL_FILE_2003 = "2003";
public void exportExcel(String title, Collection<T> dataset, OutputStream out, String version) {
if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) {
exportExcel2003(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
} else {
exportExcel2007(title, null, dataset, out, "yyyy-MM-dd hh:mm:ss");
}
}
public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String version) {
if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) {
exportExcel2003(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
} else {
exportExcel2007(title, headers, dataset, out, "yyyy-MM-dd hh:mm:ss");
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth(20);
XSSFCellStyle style = workbook.createCellStyle();
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(Color.GRAY));
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
XSSFFont font = workbook.createFont();
font.setBold(true);
font.setFontName("宋体");
font.setColor(new XSSFColor(Color.BLACK));
font.setFontHeightInPoints((short) 11);
style.setFont(font);
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setFillForegroundColor(new XSSFColor(Color.WHITE));
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
XSSFFont font2 = workbook.createFont();
font2.setBold(false);
font2.setFontName("宋体");
font2.setColor(new XSSFColor(Color.BLACK));
font2.setFontHeightInPoints((short) 11);
style2.setFont(font2);
XSSFRow row = sheet.createRow(0);
XSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
Field[] fields;
Field field;
XSSFRichTextString richString;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher;
String fieldName;
String getMethodName;
XSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = (T) it.next();
fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
field = fields[i];
fieldName = field.getName();
if ("serialVersionUID".equals(fieldName)) {
continue;
}
cell = row.createCell(i);
cell.setCellStyle(style2);
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[]{});
value = getMethod.invoke(t, new Object[]{});
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} finally {
}
}
}
try {
workbook.write(out);
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings({"unchecked", "rawtypes"})
public void exportExcel2003(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth(20);
HSSFCellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(HSSFColor.HSSFColorPredefined.GREY_50_PERCENT.getIndex());
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
HSSFFont font = workbook.createFont();
font.setBold(true);
font.setFontName("宋体");
font.setColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
font.setFontHeightInPoints((short) 11);
style.setFont(font);
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.HSSFColorPredefined.WHITE.getIndex());
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
HSSFFont font2 = workbook.createFont();
font2.setBold(false);
style2.setFont(font2);
HSSFRow row = sheet.createRow(0);
HSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
}
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
Field[] fields;
Field field;
HSSFRichTextString richString;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher;
String fieldName;
String getMethodName;
HSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = (T) it.next();
fields = t.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
field = fields[i];
fieldName = field.getName();
if ("serialVersionUID".equals(fieldName)) {
continue;
}
cell = row.createCell(i);
cell.setCellStyle(style2);
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[]{});
value = getMethod.invoke(t, new Object[]{});
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = p.matcher(textValue);
if (matcher.matches()) {
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
public void listToExcel(String[] titles, List<List<Object>> valueList, String fileName, String sheetName, HttpServletResponse response) {
try {
response.setContentType("application/x-download");
fileName = URLEncoder.encode(fileName, "UTF-8");
response.addHeader("Content-Disposition", "attachement;filename=" + fileName);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFDataFormat format = workbook.createDataFormat();
HSSFSheet sheet = workbook.createSheet();
if (sheetName != null && sheetName.trim().length() >0 ) {
workbook.setSheetName(0, sheetName);
}
HSSFRow row = sheet.createRow(0);
HSSFCell cell;
Set<String> set = new HashSet<>();
for (int i = 0; i < titles.length; i++) {
String title = titles[i];
cell = row.createCell(i);
cell.setCellType(CellType.STRING);
cell.setCellValue(title);
}
for (int j = 0; j < valueList.size(); j++) {
List<Object> values = valueList.get(j);
row = sheet.createRow(j + 1);
for (int m = 0; m < values.size(); m++) {
cell = row.createCell(m);
cell.setCellType(CellType.STRING);
if (values.get(m) != null) {
cell.setCellValue(values.get(m).toString());
} else {
cell.setCellValue("");
}
}
}
OutputStream out = response.getOutputStream();
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public String getCellValue(Cell cell) {
String value = "";
if (cell != null) {
switch (cell.getCellTypeEnum()) {
case NUMERIC:
value = cell.getNumericCellValue() + "";
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date date = cell.getDateCellValue();
if (date != null) {
value = new SimpleDateFormat("yyyy-MM-dd").format(date);
} else {
value = "";
}
} else {
value = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
case STRING://字符串
value = cell.getStringCellValue();
break;
case BOOLEAN://boolean类型
value = cell.getBooleanCellValue() + "";
break;
case BLANK://空值
value = "";
break;
case ERROR://错误类型
value = "非法字符";
break;
default:
value = "未知类型";
}
}
return value.trim();
}
}