Controller中接收form表單提交的文件域:
public Map importConsumer(@RequestParam("file") MultipartFile file)
讀取Excel工具類 這裏我以Consumer實體類來寫,大家可以自行封裝:
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<Consumer> getExcelInfo(String fileName, MultipartFile Mfile)
{
// 把spring文件上傳的MultipartFile轉換成CommonsMultipartFile類型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; // 獲取本地存儲路徑
File file = new File("D:\\fileupload");
// 創建一個目錄 (它的路徑名由當前 File 對象指定,包括任一必須的父路徑。)
if(!file.exists())
file.mkdirs();
// 新建一個文件
File file1 = new File("D:\\fileupload" + new Date().getTime() + ".xlsx");
// 將上傳的文件寫入新建的文件中
try
{
cf.getFileItem().write(file1);
}
catch (Exception e)
{
e.printStackTrace();
}
// 初始化客戶信息的集合
List<Consumer> customerList = new ArrayList<Consumer>();
// 初始化輸入流
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裏面的內容讀取客戶信息
customerList = 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 customerList;
}
/**
* 根據excel裏面的內容讀取客戶信息
*
* @param is
* 輸入流
* @param isExcel2003
* excel是2003還是2007版本
* @return
* @throws IOException
*/
public List<Consumer> getExcelInfo(InputStream is, boolean isExcel2003)
{
List<Consumer> customerList = null;
try
{
/** 根據版本選擇創建Workbook的方式 */
Workbook wb = null;
// 當excel是2003時
if(isExcel2003)
{
wb = new HSSFWorkbook(is);
}
else
{// 當excel是2007時
wb = new XSSFWorkbook(is);
}
// 讀取Excel裏面客戶的信息
customerList = readExcelValue(wb);
}
catch (IOException e)
{
e.printStackTrace();
}
return customerList;
}
/**
* 讀取Excel裏面客戶的信息
* @param wb
* @return
*/
private List<Consumer> 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<Consumer> customerList=new ArrayList<Consumer>();
Consumer consumer;
//循環Excel行數,從第二行開始。標題不入庫
for(int r=1;r<totalRows;r++){
Row row = sheet.getRow(r);
if (row == null) continue;
consumer = new Consumer();
//循環Excel的列
for(int c = 0; c <this.totalCells; c++){
Cell cell = row.getCell(c);
cell.setCellType(CellType.STRING);
if(null != cell)
{
if(c == 0)
{
consumer.setName(cell.getStringCellValue()); // 姓名
}
else if(c == 1)
{
consumer.setPhone(cell.getStringCellValue()); // 手機號碼
}
else if(c == 2)
{
consumer.setEmail(cell.getStringCellValue()); // 客戶簡稱
}
else if(c == 3)
{
consumer.setCreateUserId(cell.getStringCellValue()); //所屬訪員賬號
}
}
}
//添加客戶
customerList.add(consumer);
}
return customerList;
}
}
Service裏面調用:
public Map importConsumer(MultipartFile file,Users currentUser)
{
Map<String, Object> map = new HashMap<String, Object>();
boolean b = false;
// 創建處理EXCEL
ReadExcel readExcel = new ReadExcel();
// 解析excel,獲取客戶信息集合。
List<Consumer> ConsumerList = readExcel.getExcelInfo(file.getOriginalFilename(), file);
if(ConsumerList != null)
{
b = true;
map.put("code", 0);
}
else
{
map.put("code", -1);
}
map.put("msg", "");
for(Consumer consumer:ConsumerList)
{
String guid = java.util.UUID.randomUUID().toString();
consumer.setId(guid);
consumer.setCompanyId(currentUser.getCompanyId());
consumer.setCreateTime(formatter.format(new Date()));
consumerDao.insert(consumer); //或者進行批量保存
}
return map;
}
注意會出現異常:java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap
這是缺少jar包,需要下載commons-collections4-4.1.jar,然後放在lib下面,build path 加入到項目裏面去.
cell.getStringCellValue()
這句代碼也可能報異常,獲取單元格的數據都爲String類型,單元格的數據還可能是其他類型數據,
循環excel列需要設置一下都轉成String類型,row.getCell(0).setCellType(CellType.STRING);
基礎代碼,大家需要自行擴展。