一、前言
- 初始:起因是需要通过Excel表格的形式将数据导入到数据库中,但因为以前的人使用了ExcelUtil这个工具类,本着少些改动的原则,就没有用POI的方式操作Excel表,而是用原有的工具类进行操作
- 整体功能:从前端接收Excel文件,由于ExcelUtil只支持xls格式,所以如果是xlsx格式,还需要使用e-iceblue转换格式,然后将Excel文件中的数据取出,并导入到数据库中
- 不足:使用e-iceblue转换格式的过程中会生成一个冗余的中间文件,而且我尝试了很多种办法都没办法删掉它;转换过程需要一定时间;需要更新pom.xml,而且容易报错
- 后续优化:尝试使用POI的方式操作Excel表导入;批量插入,别一条一条插
二、步骤
package com.ev_image.gdwebgl.tools;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
public class ExcelUti {
public static <T> void listMapToExcel(
Map<Map<String,List>,LinkedHashMap> listMap,
OutputStream out
) throws Exception {
if (listMap == null || listMap.size() == 0) {
return;
}
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
for (Map.Entry<Map<String,List>, LinkedHashMap> entry : listMap.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
Map<String,List> obj=entry.getKey();
LinkedHashMap fieldMap=entry.getValue();
for (Map.Entry<String, List> item : obj.entrySet())
{
List list=item.getValue();
String sheetName=item.getKey();
double sheetNum = Math.ceil(list.size() / new Integer(65535).doubleValue());
for (int i = 0; i < sheetNum; i++) {
if (1 == sheetNum) {
WritableSheet sheet = wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
} else {
WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
int firstIndex = i * 65535;
int lastIndex = (i + 1) * 65535 - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * 65535 - 1;
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
}
}
}
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
if (e instanceof Exception) {
throw (Exception) e;
} else {
throw new Exception("导出Excel失败");
}
}
}
public static <T> void listToExcel(
List<T> list,
LinkedHashMap<String, String> fieldMap,
String sheetName,
int sheetSize,
OutputStream out
) throws Exception {
if (list == null || list.size() == 0) {
return;
}
if (sheetSize > 65535 || sheetSize < 1) {
sheetSize = 65535;
}
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
for (int i = 0; i < sheetNum; i++) {
if (1 == sheetNum) {
WritableSheet sheet = wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
} else {
WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
int firstIndex = i * sheetSize;
int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1;
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
}
}
if (sheetNum == 0) {
WritableSheet sheet = wwb.createSheet(sheetName, 0);
fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
if (e instanceof Exception) {
throw (Exception) e;
} else {
throw new Exception("导出Excel失败");
}
}
}
public static <T> void listToExcel(
List<T> list,
LinkedHashMap<String, String> fieldMap,
String sheetName,
OutputStream out
) throws Exception {
listToExcel(list, fieldMap, sheetName, 65535, out);
}
public static <T> void listToExcel(
List<T> list,
LinkedHashMap<String, String> fieldMap,
String sheetName,
int sheetSize,
HttpServletResponse response
) throws Exception {
String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
response.reset();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
try {
OutputStream out = response.getOutputStream();
listToExcel(list, fieldMap, sheetName, sheetSize, out);
} catch (Exception e) {
e.printStackTrace();
if (e instanceof Exception) {
throw (Exception) e;
} else {
throw new Exception("导出Excel失败");
}
}
}
public static <T> void listToExcel(
List<T> list,
LinkedHashMap<String, String> fieldMap,
String sheetName,
HttpServletResponse response
) throws Exception {
listToExcel(list, fieldMap, sheetName, 65535, response);
}
public static <T> List<T> excelToList(
InputStream in,
String sheetName,
Class<T> entityClass,
LinkedHashMap<String, String> fieldMap,
String[] uniqueFields
) throws Exception {
List<T> resultList = new ArrayList<T>();
try {
Workbook wb = Workbook.getWorkbook(in);
Sheet sheet = wb.getSheet(sheetName);
int realRows = 0;
for (int i = 0; i < sheet.getRows(); i++) {
int nullCols = 0;
for (int j = 0; j < sheet.getColumns(); j++) {
Cell currentCell = sheet.getCell(j, i);
if (currentCell == null || "".equals(currentCell.getContents().toString())) {
nullCols++;
}
}
if (nullCols == sheet.getColumns()) {
break;
} else {
realRows++;
}
}
if (realRows <= 1) {
throw new Exception("Excel文件中没有任何数据");
}
Cell[] firstRow = sheet.getRow(0);
String[] excelFieldNames = new String[firstRow.length];
for (int i = 0; i < firstRow.length; i++) {
excelFieldNames[i] = firstRow[i].getContents().toString().trim();
}
boolean isExist = true;
List<String> excelFieldList = Arrays.asList(excelFieldNames);
for (String cnName : fieldMap.keySet()) {
if (!excelFieldList.contains(cnName)) {
isExist = false;
break;
}
}
if (!isExist) {
throw new Exception("Excel中缺少必要的字段,或字段名称有误");
}
LinkedHashMap<String, Integer> colMap = new LinkedHashMap<String, Integer>();
for (int i = 0; i < excelFieldNames.length; i++) {
colMap.put(excelFieldNames[i], firstRow[i].getColumn());
}
Cell[][] uniqueCells = new Cell[uniqueFields.length][];
for (int i = 0; i < uniqueFields.length; i++) {
int col = colMap.get(uniqueFields[i]);
uniqueCells[i] = sheet.getColumn(col);
}
for (int i = 1; i < realRows; i++) {
int nullCols = 0;
for (int j = 0; j < uniqueFields.length; j++) {
String currentContent = uniqueCells[j][i].getContents();
Cell sameCell = sheet.findCell(currentContent,
uniqueCells[j][i].getColumn(),
uniqueCells[j][i].getRow() + 1,
uniqueCells[j][i].getColumn(),
uniqueCells[j][realRows - 1].getRow(),
true);
if (sameCell != null) {
nullCols++;
}
}
if (nullCols == uniqueFields.length) {
throw new Exception("Excel中有重复行,请检查");
}
}
for (int i = 1; i < realRows; i++) {
T entity = entityClass.newInstance();
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
String cnNormalName = entry.getKey();
String enNormalName = entry.getValue();
int col = colMap.get(cnNormalName);
String content = sheet.getCell(col, i).getContents().toString().trim();
setFieldValueByName(enNormalName, content, entity);
}
resultList.add(entity);
}
} catch (Exception e) {
e.printStackTrace();
if (e instanceof Exception) {
throw (Exception) e;
} else {
e.printStackTrace();
throw new Exception("导入Excel失败");
}
}
return resultList;
}
private static Object getFieldValueByName(String fieldName, Object o) throws Exception {
Object value = null;
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
value = field.get(o);
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
return value;
}
private static Field getFieldByName(String fieldName, Class<?> clazz) {
Field[] selfFields = clazz.getDeclaredFields();
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
return null;
}
private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
Object value = null;
String[] attributes = fieldNameSequence.split("\\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
Object fieldObj = getFieldValueByName(attributes[0], o);
String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
private static void setFieldValueByName(String fieldName, Object fieldValue, Object o) throws Exception {
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
Class<?> fieldType = field.getType();
if (String.class == fieldType) {
field.set(o, String.valueOf(fieldValue));
} else if ((Integer.TYPE == fieldType)
|| (Integer.class == fieldType)) {
field.set(o, Integer.parseInt(fieldValue.toString()));
} else if ((Long.TYPE == fieldType)
|| (Long.class == fieldType)) {
field.set(o, Long.valueOf(fieldValue.toString()));
} else if ((Float.TYPE == fieldType)
|| (Float.class == fieldType)) {
field.set(o, Float.valueOf(fieldValue.toString()));
} else if ((Short.TYPE == fieldType)
|| (Short.class == fieldType)) {
field.set(o, Short.valueOf(fieldValue.toString()));
} else if ((Double.TYPE == fieldType)
|| (Double.class == fieldType)) {
field.set(o, Double.valueOf(fieldValue.toString()));
} else if (Character.TYPE == fieldType) {
if ((fieldValue != null) && (fieldValue.toString().length() > 0)) {
field.set(o, Character.valueOf(fieldValue.toString().charAt(0)));
}
} else if (BigDecimal.class == fieldType) {
field.set(o, BigDecimal.valueOf(Double.parseDouble(fieldValue.toString())));
} else if (Date.class == fieldType) {
field.set(o, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fieldValue.toString()));
} else {
field.set(o, fieldValue);
}
} else {
throw new Exception(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
}
private static void setColumnAutoSize(WritableSheet ws, int extraWith) {
for (int i = 0; i < ws.getColumns(); i++) {
int colWith = 0;
for (int j = 0; j < ws.getRows(); j++) {
String content = ws.getCell(i, j).getContents().toString();
int cellWith = content.length();
if (colWith < cellWith) {
colWith = cellWith;
}
}
ws.setColumnView(i, colWith + extraWith);
}
}
private static <T> void fillSheet(
WritableSheet sheet,
List<T> list,
LinkedHashMap<String, String> fieldMap,
int firstIndex,
int lastIndex
) throws Exception {
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
for (int i = 0; i < cnFields.length; i++) {
Label label = new Label(i, 0, cnFields[i]);
sheet.addCell(label);
}
if (list != null && list.size() != 0) {
int rowNo = 1;
for (int index = firstIndex; index <= lastIndex; index++) {
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
Label label = new Label(i, rowNo, fieldValue);
sheet.addCell(label);
}
rowNo++;
}
}
setColumnAutoSize(sheet, 5);
}
}
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.xls</artifactId>
<version>12.9.1</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
- 若配置的仓库不起作用,在maven的setting.xml文件中找到如下位置,在mirrorOf位置的*后面加上!com.e-iceblue
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*,!com.e-iceblue</mirrorOf>
<name>阿里云公共仓库</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
@Override
public Object insertCableLineInfoByExcel(MultipartFile file){
try{
InputStream inputStream=file.getInputStream();
if (file.getOriginalFilename().endsWith("xlsx")){
Workbook workbook=new Workbook();
workbook.loadFromHtml(inputStream);
workbook.saveToFile(file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."))+".xls", ExcelVersion.Version97to2003);
File fileTemp=new File(file.getOriginalFilename().substring(0,file.getOriginalFilename().indexOf("."))+".xls");
inputStream=new FileInputStream(fileTemp);
}
String sheetname="Sheet1";
EvCablelineinfor evCablelineinfor=new EvCablelineinfor();
LinkedHashMap<String, String> fieldMap = new LinkedHashMap<>();
fieldMap.put("编号", "id");
fieldMap.put("线路编号", "loopid");
fieldMap.put("线路名称", "loopname");
fieldMap.put("电缆名称", "cablelinename");
fieldMap.put("起始设备", "startdevice");
fieldMap.put("终止设备", "enddevice");
fieldMap.put("电缆长度", "cablelength");
fieldMap.put("弧线类型", "arctype");
fieldMap.put("运行状态", "runstatus");
fieldMap.put("覆盖类型", "covertype");
String[] uniqueFields=new String[1];
uniqueFields[0]="编号";
List list = ExcelUti.excelToList(inputStream,sheetname,evCablelineinfor.getClass(),fieldMap,uniqueFields);
System.out.println(list.size());
int isSuccess=0;
for(int i=0;i<list.size();i++){
isSuccess=evCablelineinforMapper.insertSelective((EvCablelineinfor) list.get(i));
}
if(isSuccess<1){
return ResultUtil.error("excel表格导入失败");
}
return ResultUtil.success("excel表格导入成功");
} catch (Exception e){
return ResultUtil.error("excel表格格式报错");
}
}
参考