说明:数据库使用mysql,导入的字段类型只能是有varchar,Date 类型
火狐导出文件时做特殊设置,不能用url编码
ExcelUtil.java:
package com.lw.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFFont;
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.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.CollectionUtils;
/**
* Excel组件
*
* @author david
* @version 1.0
* @since 1.0
*/
public class ExcelUtil {
/**
* Excel 2003
*/
private final static String XLS = "xls";
/**
* Excel 2007
*/
private final static String XLSX = "xlsx";
/***
* 导入Excel数据
*
* 1、读取excel数据
* 2、校验数据的合法性(日期,金额,字符长度(和数据库结构比较))
* 3、合法数据绑定到bean对象中(反射)
* 4、得到数据层面校验通过的bean对象集合,
*
* @param file
* 导入数据文件
* @param entityClass
* bean对象类型bean.class
* @param sheetIndex
* sheet索引
* @param columnArray
* 字段列数组 (需要导入的字段数组)
* @param checkColumn
* 需要校验格式的字段列Map
* @throws IOException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws InstantiationException
* @throws SQLException
* @throws IllegalAccessException
* @throws ParseException
*/
public static List excelToList(File file, Integer sheetIndex, Class entityClass, String[] columnArray,
Map checkColumn) throws IOException, SecurityException, NoSuchFieldException,
InstantiationException, SQLException, IllegalAccessException, ParseException {
List list = new ArrayList();
Workbook workbook = null;
if (XLS.equalsIgnoreCase(FilenameUtils.getExtension(file.getName()))) {
workbook = new HSSFWorkbook(new FileInputStream(file));
} else if (XLSX.equalsIgnoreCase(FilenameUtils.getExtension(file.getName()))) {
workbook = new XSSFWorkbook(new FileInputStream(file));
} else {
throw new IOException("导入excel出错,不支持文件类型!");
}
if (sheetIndex == null) {
sheetIndex = 0;
}
if ((sheetIndex + 1) > workbook.getNumberOfSheets()) {
throw new IndexOutOfBoundsException("导入excel出错,指定sheet索引越界!");
}
// sheet中要导出的列
if (columnArray == null || columnArray.length < 1) {
throw new NullPointerException("导入excel出错,导入列设置错误!");
}
// 拿到sheet
Sheet sheet = workbook.getSheetAt(sheetIndex);
String sheetName = sheet.getSheetName(); // sheetName 使用表名称
// 解析公式结果
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
// 每个sheet中的数据
List
DBDataUtil.java:
package com.lw.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class DBDataUtil {
private static String url = "jdbc:mysql://172.0.0.1:3306/dbName?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull";
private static String username = "root";
private static String password = "root";
private static String driverClassName = "com.mysql.jdbc.Driver";
/**
* 查询表的字段,封装成List
*
* @param tableName
* 表名
* @param schemaName
* 数据库名
* @return
* @throws SQLException
*/
public static List getMySqlColumnDatas(String tableName, String schemaName) throws SQLException {
String SQLColumns = " select COLUMN_NAME,DATA_TYPE,column_comment,numeric_scale,numeric_precision,character_maximum_length,ordinal_position from information_schema.COLUMNS where table_name = '"
+ tableName + "'" + " and TABLE_SCHEMA='" + schemaName + "' " + " ORDER by ordinal_position";
Connection con = getConnection();
PreparedStatement ps = con.prepareStatement(SQLColumns);
List columnList = new ArrayList();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String name = rs.getString(1);
String lowName = getColumnBeanName(name); // 将XXX_XXX转换成xxxXxx的格式
String type = rs.getString(2).toUpperCase(); // mysql 区分大小写
String javaType = getType(rs.getString(2), rs.getString(4), rs.getString(5)); // mysql
// 区分大小写
String comment = rs.getString(3);
String dataScale = rs.getString(4);
String dataPrecision = rs.getString(5);
String dataMaxLength = rs.getString(6);
ColumnData cd = new ColumnData(name, lowName, type, javaType, comment, dataScale, dataPrecision,
dataMaxLength);
columnList.add(cd);
}
rs.close();
ps.close();
con.close();
return columnList;
}
public static Connection getConnection() throws SQLException {
try {
Class.forName(driverClassName);
} catch (Exception e) {
e.printStackTrace();
}
return DriverManager.getConnection(url, username, password);
}
private static String getColumnBeanName(String column) {
String[] split = column.split("_");
StringBuffer columnVal = new StringBuffer();
if (split.length > 1) {
for (int i = 0; i < split.length; i++) {
String colVal = "";
if (i == 0) {
colVal = split[i].toLowerCase();
columnVal.append(colVal);
} else {
colVal = split[i].substring(0, 1).toUpperCase()
+ split[i].substring(1, split[i].length()).toLowerCase();
columnVal.append(colVal);
}
}
columnVal.toString();
} else {
String colVal = column.toLowerCase();
columnVal.append(colVal);
}
return columnVal.toString();
}
/***
* 获取java类型
*
* @param type
* 数据库数据类型
* @param dataScale
* 小数位数
* @param dataPrecision
* 数据精度
* @return
*/
private static String getType(String type, String dataScale, String dataPrecision) {
type = type.toLowerCase();
if ("char".equalsIgnoreCase(type) || "varchar".equalsIgnoreCase(type) || "varchar2".equalsIgnoreCase(type)) {
return "java.lang.String";
} else if ("NUMBER".equalsIgnoreCase(type) || "numeric".equalsIgnoreCase(type)) {//
if ((dataScale != null && !dataScale.equals("") && !dataScale.equals("0"))) {
if (dataPrecision != null && dataPrecision.equals("38")) {
return "java.math.BigDecimal";
} else {
return "java.lang.Double";
}
} else {
if (dataPrecision != null && dataPrecision.equals("38")) {
return "java.math.BigDecimal";
} else {
return "java.lang.Long";
}
}
} else if ("decimal".equalsIgnoreCase(type)) {
return "java.math.BigDecimal";
} else if ("DATE".equalsIgnoreCase(type)) {
return "java.util.Date";
} else if ("DATETIME".equalsIgnoreCase(type)) {
return "java.util.Date";
} else if ("BLOB".equalsIgnoreCase(type)) {
return "java.sql.Blob";
} else if ("CLOB".equalsIgnoreCase(type)) {
return "java.sql.Clob";
} else if ("int".equalsIgnoreCase(type)) {
return "java.lang.Integer";
} else if ("TINYINT".equalsIgnoreCase(type)) {
return "java.lang.Boolean";
} else if ("double".equalsIgnoreCase(type)) {
return "java.math.BigDecimal";
} else if ("datetime".equalsIgnoreCase(type)) {
return "java.util.Date";
}
return null;
}
}
ColumnData.java
package com.lw.util;
/**
* 表字段类
* @author david
*/
public class ColumnData {
private String columnName;
private String dataType;
private String comments;
private String columnLowName;
private String dataScale;
private String dataPrecision;
private String javaType; // java数据类型
private String dataMaxLength; // 最大长度
public ColumnData() {}
public ColumnData(String columnName,
String columnLowName,
String dataType,
String javaType,
String comments,
String dataScale,
String dataPrecision,
String dataMaxLength) {
this.columnName = columnName;
this.columnLowName = columnLowName;
this.dataType = dataType;
this.javaType = javaType;
this.comments = comments;
this.dataScale = dataScale;
this.dataPrecision = dataPrecision;
this.dataMaxLength = dataMaxLength;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getColumnLowName() {
return columnLowName;
}
public void setColumnLowName(String columnLowName) {
this.columnLowName = columnLowName;
}
public String getDataScale() {
return dataScale;
}
public void setDataScale(String dataScale) {
this.dataScale = dataScale;
}
public String getDataPrecision() {
return dataPrecision;
}
public void setDataPrecision(String dataPrecision) {
this.dataPrecision = dataPrecision;
}
public String getJavaType() {
return javaType;
}
public void setJavaType(String javaType) {
this.javaType = javaType;
}
public String getDataMaxLength() {
return dataMaxLength;
}
public void setDataMaxLength(String dataMaxLength) {
this.dataMaxLength = dataMaxLength;
}
}