您的位置:首页 > 编程语言 > Java开发

Java实现Excel表格数据批量导入

2017-10-25 12:36 1316 查看
一、前台上传Excel表格,传递到后台

<input type="file" name="excel" id="excel" accept="application/vnd.ms-excel"/>

其中accept限定上传的文件只能是.xls文件
function uploadFile() {
var file = document.getElementById("excel").files[0];
if (file) {
var formData = new FormData();
formData.append("excel", file);
$.ajax({
url: 'cdc/providentFund/importProvidentFund',
type: 'POST',
cache: false,
data: formData,
//这个参数是jquery特有的,不进行序列化,因为我们不是json格式的字符串,而是要传文件
processData: false,
//注意这里一定要设置contentType:false,不然会默认为传的是字符串,这样文件就传不过去了
contentType: false,
success: function (data) {
if (data.code==200){
swal({
title: "导入成功",
type: "success"
});
}else{
swal({
title: "导入失败",
type: "error"
});
}
}
});
}
else {
swal({
title: "请选择上传文件",
type: "warning"
})
}
}

二,后台接收并录入数据库
导包,pom文件添加依赖

<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>Java代码:
/**
* Excel表格数据导入
* @param request
* @param response
*/
@PostMapping(value = "importProvidentFund")
@PreAuthorize("hasAuthority('edit')")
@ResponseBody
public JSONObject importExcel(HttpServletRequest request, HttpServletResponse response){
JSONObject jsonObject=new JSONObject();
jsonObject.put("code",200);
Part part=null;
try {
part=request.getPart("excel");
} catch (IOException e) {
e.printStackTrace();
} catch (ServletException e) {
e.printStackTrace();
}
Workbook workbook =null;
try {
workbook = new HSSFWorkbook(part.getInputStream());//获取Excel文件
} catch (IOException e) {
e.printStackTrace();
}
Sheet sheet=workbook.getSheetAt(0);//获取表格,第一个表格
// 获取sheet中最后一行行号
int lastRowNum = sheet.getLastRowNum();//获取表格有多少行数据
for (int i = 1; i <= lastRowNum; i++) {
//代码解释:获取当前行中的内容
Row row = sheet.getRow(i); //获取行
int cell = row.getLastCellNum(); //获取有多少列
if(row !=null && cell!=0){
ProvidentFund providentFund=new ProvidentFund(); //将每一项的值添加到对象中
providentFund.setEmployeeAccountNumber(row.getCell(0).getStringCellValue());
providentFund.setPersonName(row.getCell(1).getStringCellValue());
//会损失精度,转成字符串在生成BigDecimal对象
providentFund.setBeforeMonthPay(getValue(row.getCell(2)));
providentFund.setDepositBase(getValue(row.getCell(3)));
providentFund.setAfterMonthPay(getValue(row.getCell(4)));
providentFund.setAdjustMoney(getValue(row.getCell(5)));
Date date =new Date();
providentFund.setCreateTime(date);
providentFund.setUpdateTime(date);
boolean b = providentFundService.insert(providentFund);//保存到数据库中
if (!b){
jsonObject.put("code",500);
}
}
}
return jsonObject;
}其中getValue方法是将double类型的值转换为BigDecimal对象
private BigDecimal getValue(Cell cell){
return BigDecimal.valueOf(cell.getNumericCellValue());
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel 数据导入