上传、解析excel并保存其内容到数据库:
controller层:
/**
* 读取Excel数据到数据库
* @param file
* @param request
* @return
* @throws IOException
* @author lp
*/
@RequestMapping(value="/readExcel",method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> readExcel(
@RequestParam(value="file",required = false) MultipartFile file,
HttpServletRequest request,HttpSession session) throws IOException{
User user = (User) request.getSession().getAttribute("user");
Map<String,Object> resultMap = new HashMap<String,Object>();
//判断是否已经上传过
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
Date a = excelService.getLatestDate();
if(a != null){
String dateNowStr = sdf.format(new Date());
String date = sdf.format(a);
if(dateNowStr.equals(date)){
resultMap.put("status",1);
resultMap.put("msg", "不可重复上传");
return resultMap;
}
}
//判断文件是否为空
if(file == null){
resultMap.put("status",1);
resultMap.put("msg", "上传失败,文件为空");
return resultMap;
}
String name = file.getOriginalFilename();
long size = file.getSize();
if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){
resultMap.put("status",1);
resultMap.put("msg", "上传失败,文件为空");
return resultMap;
}
//读取Excel数据到List中
List<ArrayList<String>> list = new ExcelRead().readExcel(file);
//list中存的就是excel中的数据,可以根据excel中每一列的值转换成你所需要的值(从0开始),如:
Excel excel = null;
List<Excel> listExcel = new ArrayList<Excel>();
for(ArrayList<String> arr:list){
excel= new Excel();
excel.setName(arr.get(0));//每一行的第一个单元格
excel.setBank(arr.get(1));
excel.setFull(arr.get(2));
excel.setActual(arr.get(3));
excel.setBase(arr.get(4));
excel.setProject(arr.get(5));
excel.setSubsidy(arr.get(6));
excel.setTax(arr.get(7));
excel.setBonus(arr.get(8));
excel.setPay(arr.get(9));
excel.setAccommodation(arr.get(10));
excel.setTravel(arr.get(11));
excel.setSubsidies(arr.get(12));
excel.setInsurance(arr.get(13));
excel.setPractical(arr.get(14));
excel.setAddPeople(user.getUsercode());
excel.setAddTime(new Date());
listExcel.add(excel);
}
if(excelService.saveBatchInsert(listExcel)>0){
resultMap.put("status", 0);
resultMap.put("msg", "上传成功");
}else{
resultMap.put("status", 1);
resultMap.put("msg", "上传失败");
}
return resultMap;
}
Util类:
ExcelRead类:
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
* 读取Excel
* @author lp
*
*/
public class ExcelRead {
public int totalRows; //sheet中总行数
public static int totalCells; //每一行总单元格数
/**
* read the Excel .xlsx,.xls
* @param file jsp中的上传文件
* @return
* @throws IOException
*/
public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
return null;
}else{
String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
if(!ExcelUtil.EMPTY.equals(postfix)){
if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
}
/**
* read the Excel 2010 .xlsx
* @param file
* @param beanclazz
* @param titleExist
* @return
* @throws IOException
*/
@SuppressWarnings("deprecation")
public List<ArrayList<String>> readXlsx(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new XSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 1;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//读取列,从第一列开始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* read the Excel 2003-2007 .xls
* @param file
* @param beanclazz
* @param titleExist
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXls(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流读取文件
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 创建文档
wb = new HSSFWorkbook(input);
//读取sheet(页)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//读取Row,从第二行开始
for(int rowNum = 1;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//读取列,从第一列开始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
service类:
将解析出来的excel,保存到数据库
//保存工资单
public int saveBatchInsert(List<Excel> list){
return excelMapper.batchInsert(list);
}
dao层:
int batchInsert(List<Excel> list); //保存工资单
mapper层:
<insert id="batchInsert" parameterType="java.util.List" useGeneratedKeys="false" keyProperty="id">
insert into baseinfo
(name,bank,full,actual,base,project,subsidy,tax,bonus,pay,accommodation,travel,subsidies,insurance,practical,addPeople,addTime)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.name},
#{item.bank},
#{item.full},
#{item.actual},
#{item.base},
#{item.project},
#{item.subsidy},
#{item.tax},
#{item.bonus},
#{item.pay},
#{item.accommodation},
#{item.travel},
#{item.subsidies},
#{item.insurance},
#{item.practical},
#{item.addPeople},
#{item.addTime}
)
</foreach>
</insert>
前端jsp页面:
<form id="uploadForm" enctype="multipart/form-data">
<span>解析工资单:</span>
<input type="file" name="file" style="width: 170px" />
</form>
<button id="upload" onclick="addappbanner()" class="btn btn-info" >上传文件</button>
js页面:
function addappbanner() {
var file = new FormData($('#uploadForm')[0]);
$.ajax({
type: 'post',
url: "<%=path %>"+"/excel/readExcel.do",
data: file,
cache: false,
processData: false,
contentType: false,
success: function (result) {
if(result.status == 0){
alert(result.msg);
parent.location.reload();
} else {
alert(result.msg);
}
}
})
}
所需jar包:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15-beta1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.16-beta1</version>
</dependency>