通過maven導入上傳文件及解析excel的包:
①:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
②:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
一:JSP代碼:定義一個input標簽,type屬性為file,外層定義一個from表單加上enctype="multipart/form-data"屬性.具體代碼如下:
<form id="QueryForm" action="${ctx}/addData/upLoad.do" method="post"
enctype="multipart/form-data" onsubmit="return check();">
<div class="row">
<div class="col-sm-6" style="width: 50%;">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">請選擇上傳的文件:</h3>
<div class="box-body">
<input id="excel_file" class="form-control" type="file" name="filename" accept="xlsx" size="80" />
</div>
<span class="box-title"><c:if test="${msg !=''}">${msg}</c:if>
</span>
<input class="btn btn-primary pull-right" id="excel_button" type="submit" value="導入" />
</div>
</div>
</div>
</div>
</form>
二:controller層:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.beipei.dal.dataobject.OrderformDO;
import com.beipei.service.common.facade.OrderformService;
@Controller
@RequestMapping("/addData")
public class AddDataContorller {
@Value("${application.jsp.path}")
private String jspPath;
@Autowired
private OrderformService orderformService;
@RequestMapping("/addDatas.do")
public String addDatas(){
return jspPath+"czgn/AddData/AddData.jsp";
}
/**接收上傳的文件*/
@RequestMapping("/upLoad.do")
public String upLoad(@RequestParam(value="filename") MultipartFile file,Map<String, Object> map){
String msg = "";
//獲取文件名
String name = file.getOriginalFilename();
//定義一個本地文件副本(路徑+文件名),用來接收前端上傳的文件內容容
String localfile = "/app/newFile.xlsx";//需要修改文件路徑
try{
List<OrderformDO> orderformDOs = orderformService.excelImport(name, file,localfile);
System.out.println(orderformDOs);
msg = "解析成功,總共"+orderformDOs.size()+"條!";
}catch(Exception e){
e.printStackTrace();
msg ="導入失敗......";
}
map.put("msg", msg);
return jspPath+"czgn/AddData/AddData.jsp";
}
}
三:下面是解析excel代碼,通過service層調用util包內自己寫的解析工具類
@Override
public List<OrderformDO> excelImport(String name, MultipartFile file, String localfile) {
ReadExcel ReadExcel = new ReadExcel();
List<OrderformDO> excelInfo = ReadExcel.getExcelInfo(name, file, localfile);
return excelInfo;
}
ReadExcel.java
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import com.beipei.dal.dataobject.OrderformDO;
public class ReadExcel {
// 總行數
private int totalRows = 0;
// 總條數
private int totalCells = 0;
// 錯誤信息接收器
private String errorMsg;
// 構造方法
public ReadExcel() {
}
// 獲取總行數
public int getTotalRows() {
return totalRows;
}
// 獲取總列數
public int getTotalCells() {
return totalCells;
}
// 獲取錯誤信息
public String getErrorInfo() {
return errorMsg;
}
/**
* 驗證EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath) {
if (filePath == null
|| !(WDWUtil.isExcel2003(filePath) || WDWUtil
.isExcel2007(filePath))) {
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}
/**
* 讀EXCEL文件,獲取客戶信息集合
*
* @param fielName
* @return
*/
public List<OrderformDO> getExcelInfo(String fileName,
MultipartFile Mfile, String localfile) {
File file1 = new File(localfile);//新建文件
//轉存文件,將文件轉存到本地
try {
Mfile.transferTo(file1);
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
List<OrderformDO> list = new ArrayList<OrderformDO>();
// 初始化輸入流
InputStream is = null;
try {
// 驗證文件名是否合格
if (!validateExcel(fileName)) {
return null;
}
// 根據文件名判斷文件是2003版本還是2007版本
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
// 根據新建的文件實例化輸入流
is = new FileInputStream(file1);
// 根據excel里面的內容讀取信息
list = getExcelInfo(is, isExcel2003);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return list;
}
/**
* 根據excel里面的內容讀取客戶信息
* @param is
* 輸入流
* @param isExcel2003
* excel是2003還是2007版本
* @return
* @throws IOException
*/
public List<OrderformDO> getExcelInfo(InputStream is,
boolean isExcel2003) {
List<OrderformDO> list = null;
try {
/** 根據版本選擇創建Workbook的方式 */
Workbook wb = null;
// 當excel是2003時
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {// 當excel是2007時
wb = new XSSFWorkbook(is);
}
// 讀取Excel里的信息
list = readExcelValue(wb);
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
/**
* 讀取Excel里面信息
*
* @param wb
* @return
*/
private List<OrderformDO> readExcelValue(Workbook wb) {
// 得到第一個shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行數
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列數(前提是有行數)
if (totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
List<OrderformDO> orderformDOs = new ArrayList<OrderformDO>();
// 循環Excel行數,從第二行開始。標題不入庫
for (int r = 1; r < totalRows; r++) {
OrderformDO orderformDO = new OrderformDO();
Row row = sheet.getRow(r).getCell(1).getRow();
if (row == null)
continue;
// 循環Excel的列,獲取相關信息
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
cell.setCellType(Cell.CELL_TYPE_STRING);
orderformDO.setLicensenumber(cell.getStringCellValue());
} else if (c == 1) {
cell.setCellType(Cell.CELL_TYPE_STRING);
orderformDO.setPolicyno(cell.getStringCellValue());
} else if (c == 3) {//日期>>需要轉換
if(HSSFDateUtil.isCellDateFormatted(cell)){
orderformDO.setStartdate(cell.getDateCellValue());
}
} else if (c == 4) {//日期
if(HSSFDateUtil.isCellDateFormatted(cell)){
orderformDO.setEnddate(cell.getDateCellValue());
}
}else if (c == 5) {
if(HSSFDateUtil.isCellDateFormatted(cell)){
orderformDO.setInserttimeforhis(cell.getDateCellValue());
}
}else if (c == 6) {
cell.setCellType(Cell.CELL_TYPE_STRING);
orderformDO.setComcode(cell.getStringCellValue());
}
}
}
// 添加
orderformDOs.add(orderformDO);
}
return orderformDOs;
}
}
WDWUtil.java
public class WDWUtil {
// @描述:是否是2003的excel,返回true是2003
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
// @描述:是否是2007的excel,返回true是2007
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
以上就是上傳excel文件並解析,至於如何存入數據庫這里不去做了,這個工具類返回的list可以直接存入庫中對應字段.
