JAVA匯入excel後臺儲存資料庫
//**************************************************************前端程式碼************************************************************
>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
"text/jscript" >
|
//**************************************************************後臺程式碼************************************************************
最近在做一個web專案,需要寫一個Excel檔案的匯入,由於本猿是個剛入行不就的萌新,所以找到了一些文章研究了一下,但是講的都比較混亂,於是在一邊借閱一邊的摸索中完成了匯入,先說一下思路: 1.首先是將需要匯入的文件轉換成流的形式。 2.判斷excel檔案的型別是.xlsx還是.xls格式的,將對應的格式轉換成Workbook所對應的格式,到了此處基本上一個excl檔案就已經被匯入了,並且儲存為對應的excl格式了。 3.此方法workbook.getSheetAt()可以得到你的這個檔案上的所有的sheet,我的sheet預設只有一個所以我直接取的是sheet(0)。 4.然後遍歷此sheet得到所有的Row,將每行的資料add到list中並且返回。 5.然後遍歷每一行的,得到對應的元素上的資訊,這裡需要注意一下,這個row.getCell(0)方法是從0開始的,然後就得到了你所需要到倒數的資料了,剩下的事情就是業務的處理啦。 下來我上一下,我的具體的做法。
一.環境和所需要引入的jar包。
環境:
ssm+maven
具體的檔案的上傳可以檢視我的上一篇部落格
基於springMVC的檔案上傳和下載
這裡需要注意的是這裡我們需要引入支援解析excl的工具類poi,我是直接maven直接匯入的,如下:
<!-- 匯入和匯出excel時需要的jar包 -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
到此,前期的環境的準備工作就已經全部完成了。
二.程式碼
## 匯入的方法的介面 ##
這裡需要注意下,這裡的Result的是我自己定義的一個類,你們在引用的時候自己重寫下就可以了,用Object就可以,返回個map就可以了。
import com.yonyouFintech.yangfan.commons.Result;
import com.yonyouFintech.yangfan.commons.util.DateUtil;
import com.yonyouFintech.yangfan.commons.util.ExcelUtil;
import com.yonyouFintech.yangfan.domain.YfBibliographic;
import com.yonyouFintech.yangfan.service.YfBibliographicService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
@RestController
public class yfImportExclController {
@Autowired
private YfBibliographicService yfBibliographicService;
@RequestMapping(value = "/exclImport",method = RequestMethod.POST)
public Result importExcl(@RequestParam("file") MultipartFile excl, HttpServletRequest request){
Result result = new Result();
if(!excl.isEmpty()){//說明檔案不為空
try {
String fileName = excl.getOriginalFilename();
InputStream is = excl.getInputStream();//轉化為流的形式
List<YfBibliographic> listMer = new ArrayList<YfBibliographic>();
List<Row> list = ExcelUtil.getExcelRead(fileName,is, true);
//首先是讀取行 也就是一行一行讀,然後在取到列,遍歷行裡面的行,根據行得到列的值
for (Row row : list) {
/****************得到每個元素的值start**********************/
Cell cell_0 = row.getCell(0);
Cell cell_1 = row.getCell(1);
Cell cell_2 = row.getCell(2);
Cell cell_3 = row.getCell(3);
/*****************得到每個元素的值end**********************/
/******************解析每個元素的值start*******************/
//得到列的值,也就是你需要解析的欄位的值
String bookName = ExcelUtil.getValue(cell_0);
String editor = ExcelUtil.getValue(cell_1);
String express = ExcelUtil.getValue(cell_2);
String version = ExcelUtil.getValue(cell_3);
/******************解析每個元素的值end*******************/
/****************將讀取出來的數值進行包裝start***********/
YfBibliographic yfBibliographic = new YfBibliographic();
yfBibliographic.setName(bookName);
yfBibliographic.setAuthor(editor);
yfBibliographic.setPress(express);
yfBibliographic.setEdition(version);
yfBibliographic.setStatus("1");
yfBibliographic.setExtend1(DateUtil.getCurDateStr());
listMer.add(yfBibliographic);
/**************將讀取出來的數值進行包裝end**************/
}
if(listMer.size()>0){
for (YfBibliographic item:listMer) {
yfBibliographicService.insertYfBibliographic(item);
}
}
result.setSuccess(true);
result.setSuccessMessage("匯入成功!");
}catch (Exception e){
e.printStackTrace();
result.setSuccess(false);
result.setErrorMessage("匯入出現異常!");
}
}else{
result.setSuccess(false);
result.setErrorMessage("匯入的檔案為空!");
}
return result;
}
}
判斷檔案型別的工具類
/**
* @author zhaokk
* @Date 2017-12-01
* 工具類驗證Excel文件
*/
public class WDWUtil {
/**
* @描述:是否是2003的excel,返回true是2003
* @param filePath
* @return
*/
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
/**
* @描述:是否是2007的excel,返回true是2007
* @param filePath
* @return
*/
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
/**
* 驗證是否是EXCEL檔案
* @param filePath
* @return
*/
public static boolean validateExcel(String filePath){
if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
return false;
}
return true;
}
}
獲取excel表格,每行的資料的類
import org.apache.poi.hssf.usermodel.HSSFCell;
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 java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
public class ExcelUtil {
//讀取檔案的方法
/**
* 獲取解析檔案行資料
* @param fileName : 檔案地址
* @param isTitle : 是否過濾第一行解析
* @return
* @throws Exception
*/
public static List<Row> getExcelRead(String fileName, InputStream is, boolean isTitle) throws Exception{
try {
//判斷其相容版本 呼叫了判斷版本的方法
Workbook workbook = getWorkbook(fileName,is);
Sheet sheet = workbook.getSheetAt(0);
int count = 0;
List<Row> list = new ArrayList<Row>();
for (Row row : sheet) {
// 跳過第一行的目錄
if (count == 0 && isTitle) {
count++;
continue;
}
list.add(row);
}
return list;
} catch (Exception e) {
throw e;
}
}
//判斷版本的方法
public static Workbook getWorkbook(String fileName,InputStream is) throws Exception{
Workbook workbook = null;
try {
/** 判斷檔案的型別,是2003還是2007 */
boolean isExcel2003 = true;
if (WDWUtil.isExcel2007(fileName)) {
isExcel2003 = false;
}
if (isExcel2003) {
workbook = new HSSFWorkbook(is);
} else {
workbook = new XSSFWorkbook(is);
}
} catch (Exception e) {
throw e;
}
return workbook;
}
//得到celL值的方法:
public static String getValue(Cell cell){
if(cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){
return String.valueOf(cell.getBooleanCellValue());
}else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
double value = cell.getNumericCellValue();
return new BigDecimal(value).toString();
}else if (cell.getCellType() ==HSSFCell.CELL_TYPE_STRING){
return String.valueOf(cell.getStringCellValue());
}else{
return String.valueOf(cell.getStringCellValue());
}
}
}
親測可用。此處為防止原文丟失,特將程式碼儲存此處。