poi导入excle表
场景:当我们需要插入大量数据的时候,如果我们采用原来的那种一个一个的添加,那无疑是很慢的,所以我们需要批量插入数据。那么如何批量插入呢,一是在业务中for循环插入数据,但这样不收最好的。我们可以利用动态sql进行批量插入。但数据从哪里来呢,当然可以使用java提供的poi包来导入数据。
import java.io.InputStream;
import java.lang.reflect.Field;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
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.ss.usermodel.WorkbookFactory;
public class ImportExcle {
@SuppressWarnings("unchecked")
public static <T> List<T> importDataByExcle(InputStream in, String classPath) throws Exception {
// String fileName = "D:\\picture\\3.xls";
//InputStream is = new FileInputStream(new File(path));
// Class<Chance> cls = Chance.class;
Class<?> cls = Class.forName(classPath);
String[] titles = new String[50];
Field[] fs = cls.getDeclaredFields();
for (int i = 0; i < fs.length; i++) {
titles[i] = fs[i].getName();
}
Workbook hssfWorkbook = WorkbookFactory.create(in);;
Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
/*// int index = 0;
if (path.endsWith(".xlsx")) {
hssfWorkbook = new XSSFWorkbook(is);// Excel 2007
} else if (path.endsWith(".xls")) {
hssfWorkbook = new HSSFWorkbook(is);// Excel 2003
}*/
List<T> list = new ArrayList<T>();
// 循环工作表Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
Sheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// 循环行Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
Row row = hssfSheet.getRow(rowNum);
Object instance = cls.newInstance();
if (row != null) {
for (int cell = 0; cell < row.getLastCellNum(); cell++) {
Cell cell2 = row.getCell(cell);
cell2.setCellType(CellType.STRING);
String value = cell2.getStringCellValue();
Field f = cls.getDeclaredField(titles[cell]);
f.setAccessible(true);
if (pattern.matcher(value).matches() && value.length() < 5) {
f.set(instance, Integer.valueOf(value));
} else if (isDate(value, "yyyy年MM月dd日 HH:mm:ss")) {
f.set(instance, sdf.parse(value));
} else {
f.set(instance, value);
}
}
}
list.add((T) instance);
}
}
return list;
}
public static boolean isDate(String value, String format) {
SimpleDateFormat sdf = null;
ParsePosition pos = new ParsePosition(0);// 指定从所传字符串的首位开始解析
if (value == null || value.equals("")) {
return false;
}
try {
sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
Date date = sdf.parse(value, pos);
if (date == null) {
return false;
} else {
if (pos.getIndex() > sdf.format(date).length()) {
return false;
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
利用poi和java反射实现对各种表格进行导入,需要导入那个表格就传入对应的实体类list集合。然后再通过sql语句for循环批量插入。该工具包还存在很多问题,但勉强可以用,有不足之处请指出。