1.导入依赖,这里使用的maven,主要使用的是poi3.8,建议用这个版本
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2.前端html代码,这里只介绍使用,所以页面很简单,记得要是form表单包住
<form id="uploadForm" action="" method="post" enctype="multipart/form-data">
<input type="file" name="file"/>
<input id="upload" type="button" value="上传数据"/>
</form>
3.前端ajax请求,你想啊,你肯定需要发送请求到控制层吧,我这里通过id获取了这个事件,所以建议如果您是第一次接触的话,就把下面的这个js请求用包住页面最下面,因为这样页面才会加载
//上传用户excel
$("#upload").click(function(){
$.ajax({
type : "POST",
url : "${mvcPath}/interfaceListImport/upload",
data : new FormData($('#uploadForm')[0]),
processData : false,
contentType : false,
success:function(result){
alert(result);
}
});
});
4.到控制层了,请大家注意我的url和我的控制层url是一致的,类型必须是POST,大家不用看第一个方法,第一个方法是我跳转到页面的,只需要看第二个方法,调用了service方法,因为我的导入操作是在service层,service层获取到数据,再调用dao方法层插入,不就是导入了嘛(后面是重点,仔细看)
5.先给大家看一下service接口类的方法,请注意(第一个方法是导入的方法,就是从excel导入,第二个方法是插入到数据库,请试想是不是要先获取到导入的数据,然后插入到数据库)
public void importExclData(MultipartFile excl);
public Integer insertInterfaceList(InterfaceListImport interfaceListImport) ;
6.这是serviceImpl的实现类,这一行确实有点长,这是因为我的需求excel有18列,所以写了很多相似代码(各位不要怕)
我略微解释一下,首先大家可以先把代码复制到txt记事本上,最好是Notepad++这个工具上,这样比较明显,方便看我的解释进行对比(解释开始)
(1.)看importExclData这个方法,他就是导入excel的方法,首先你得判断一下你的excel的后缀吧,大家都知道,excel有两种后缀.xlsx和xls
(2.)获取Sheet对象, Sheet sheet = workbook.getSheetAt(0);就是获取你的excel第一页数据
(3.)你得创建一个javaBean对象吧,用来接收你获取到的数据InterfaceListImport interfaceListImport; 这个大家不要觉得很厉害,就是个javaBean
(4).后面就是开始遍历,其实我的代码里也有注释,大家看看
(5.)在后面大家看到我获取数据,0-17其实是因为我的数据有18列,你的excel有几列,你就获取几列
(6)然后你讲获取的数据set到你的javabean对象里,然后执行插入操作,每获取一个javabean,你就插入一下,可能有人问为什么不用一个List把javabean全部放进去呢,然后在sql语句循环插入,其实这里有个问题的,如果你的excel数据比较小,是可以的,如果excel数据很大,就不行
大小如何区分呢?只要小于1000个数据就算小,这个1000就是你的列乘以你的行,比如:我的excel有18列,假如有10行,那数据就是18*10=180,就是180个数据了
(7)在代码中有一个ExcelUtils类大家看到了,其实他是为了提高代码的健壮性的,你想,你的excel不可能全是文本吧,也可能是数字或者其他,对吧?所以我写了一个单独的类,放在最后面(反正就是一句话,直接粘贴用就完事)
@Autowired
private InterfaceListImportMapper interfaceListImportMapper;
@Override
public void importExclData(MultipartFile excl) {
InputStream in = null;
try {
in = excl.getInputStream();
// 获取execl文件对象
Workbook workbook = null;
// 根据后缀,得到不同的Workbook子类,即HSSFWorkbook或XSSFWorkbook
if (excl.getOriginalFilename().endsWith("xlsx")) {
workbook = new XSSFWorkbook(in);//给定输入流读取文件创建XLSX操作对象
} else if (excl.getOriginalFilename().endsWith("xls")) {
workbook = new HSSFWorkbook(in);//给定输入流读取文件创建XLS操作对象
} else {
throw new Exception("文件格式不对或者文件损坏....");
}
// 获得sheet对应对象 获取第一页对象
Sheet sheet = workbook.getSheetAt(0);
// 创建Station对象容器
InterfaceListImport interfaceListImport;
// 解析sheet,获得多行数据,并放入迭代器中
Iterator<Row> ito = sheet.iterator();
int count = 0;
int sum = 0;
Row row = null;
//每次导入就把上次的删除
delInterfaceList();
while (ito.hasNext()) {
row = ito.next();
// 由于第一行是标题因此这里单独处理
if (count == 0) {
++count;
continue;
} else {
if (row != null) {
interfaceListImport = new InterfaceListImport();
String interfaceCode = ExcelUtils.getCellValue( row.getCell(0));
String interfaceName = ExcelUtils.getCellValue( row.getCell(1));
String interfaceSource = ExcelUtils.getCellValue( row.getCell(2));
String interfaceTopics = ExcelUtils.getCellValue( row.getCell(3));
String samplingWeekandMethod = ExcelUtils.getCellValue( row.getCell(4));
String uploadTime = ExcelUtils.getCellValue( row.getCell(5));
String enableStatus = ExcelUtils.getCellValue( row.getCell(6));
String serviceLife = ExcelUtils.getCellValue(row.getCell(7));
String volumeInformation = ExcelUtils.getCellValue( row.getCell(8));
String specificationVersion = ExcelUtils.getCellValue( row.getCell(9));
String transmissionParty = ExcelUtils.getCellValue( row.getCell(10));
String inspectionParty = ExcelUtils.getCellValue( row.getCell(11));
String loadingParty = ExcelUtils.getCellValue(row.getCell(12));
String synchronousParty = ExcelUtils.getCellValue( row.getCell(13));
String synchronizationRange = ExcelUtils.getCellValue( row.getCell(14));
String effectiveDate = ExcelUtils.getCellValue( row.getCell(15));
String expirationDate = ExcelUtils.getCellValue(row.getCell(16));
String timelinessAssessed = ExcelUtils.getCellValue( row.getCell(17));
char charAt = timelinessAssessed.charAt(0);
if(charAt != '是' && charAt != '否') {
timelinessAssessed = "未知";
}
interfaceListImport.setInterfaceCode(interfaceCode);
interfaceListImport.setInterfaceName(interfaceName);
interfaceListImport.setInterfaceSource(interfaceSource);
interfaceListImport.setInterfaceTopics(interfaceTopics);
interfaceListImport.setSamplingWeekandMethod(samplingWeekandMethod);
interfaceListImport.setUploadTime(uploadTime);
interfaceListImport.setEnableStatus(enableStatus);
interfaceListImport.setServiceLife(serviceLife);
interfaceListImport.setVolumeInformation(volumeInformation);
interfaceListImport.setSpecificationVersion(specificationVersion);
interfaceListImport.setTransmissionParty(transmissionParty);
interfaceListImport.setInspectionParty(inspectionParty);
interfaceListImport.setLoadingParty(loadingParty);
interfaceListImport.setSynchronousParty(synchronousParty);
interfaceListImport.setSynchronizationRange(synchronizationRange);
interfaceListImport.setEffectiveDate(effectiveDate);
interfaceListImport.setExpirationDate(expirationDate);
interfaceListImport.setTimelinessAssessed(timelinessAssessed);
//依次添加,因为oracle最大可容纳1000游标,只能依次添加
insertInterfaceList(interfaceListImport);
}
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
@Override
public Integer insertInterfaceList(InterfaceListImport interfaceListImport) {
return interfaceListImportMapper.insertInterfaceList(interfaceListImport);
}
package com.asiainfo.gbas.util;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
public class ExcelUtils {
public static String getCellValue( Cell cell )
{
if (cell != null)
{
switch (cell.getCellType())
{
case XSSFCell.CELL_TYPE_BLANK:
return null;
case XSSFCell.CELL_TYPE_BOOLEAN:
return String.valueOf( cell.getBooleanCellValue() );
case XSSFCell.CELL_TYPE_NUMERIC:
return String.valueOf( ( int ) cell.getNumericCellValue() );
case XSSFCell.CELL_TYPE_STRING:
return cell.getRichStringCellValue().toString();
}
}
return null;
}
}