ssm利用poi將excel資料匯入資料庫
POI匯入資料庫
1.前臺頁面
<form action="<%=request.getContextPath()%>/doFile.action" method="post" enctype="multipart/form-data">
請選擇檔案:<input type="file" name="excelFile"><br/>
<input type="submit" value="提交">
</form>
excelFile封裝 用 MultipartFile封裝一個實體類
2.spring中進行上傳配置
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize"><value>100000</value></property>
<property name="defaultEncoding"><value>UTF-8</value></property>
</bean>
3.後臺程式碼
4.ExcelUtils為工具類(將Excel中的資料 讀取成為List集合)
public static List<Object> ExcelForList(MultipartFile file, Class<?> beanclazz,Boolean titleExist) {
List<Object> list = new ArrayList<Object>();
try {
// IO流讀取檔案
InputStream input = file.getInputStream();
// 建立文件
Workbook wb = new HSSFWorkbook(input);
// 得到第一張工作表
Sheet sheet = wb.getSheetAt(0);
int i;
if (titleExist) {
i = 1;
} else {
i = 0;
}
// 行的遍歷
for (; i <= sheet.getLastRowNum(); i++) {
// 得到行
Row row = sheet.getRow(i);
// 單元格的遍歷
// 例項化物件
Object object = beanclazz.newInstance();
Field[] fields = beanclazz.getDeclaredFields();
int j = 0;
for (Field field : fields) {
String fieldName = field.getName();
PropertyDescriptor pd = new PropertyDescriptor(fieldName, beanclazz);
Method getMethod = pd.getWriteMethod();
Cell cell = row.getCell(j++);
try{
int type = cell.getCellType();
if (type == cell.CELL_TYPE_BOOLEAN) {
// 返回布林型別的值
boolean value = cell.getBooleanCellValue();
getMethod.invoke(object, value);
System.out.println(object);
System.out.println(value);
} else if (type == cell.CELL_TYPE_NUMERIC) {
// 返回數值型別的值
Double d = cell.getNumericCellValue();
int value = d.intValue();
getMethod.invoke(object, new Integer(value));
} else if (type == cell.CELL_TYPE_STRING) {
// 返回字串型別的值
String value = cell.getStringCellValue();
getMethod.invoke(object, new String(value));
}
}catch (Exception e) {
System.out.println("");
}
}
list.add(object);
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
5.lib包