1. 程式人生 > >excel上傳保存到數據庫 poi

excel上傳保存到數據庫 poi

情況 mes stream 實現 cell err subst import xls

使用工具:

  JQuery ocupload    jquery.ocupload-1.1.2.js

   Apache POI       poi-3.9.jar

  如果是使用maven:

   <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.9</version>   
   </dependency>  

jsp:

<form id="excelFrom" enctype="multipart/form-data" method="post">

  <input type="file" id="file" name ="file"/>

</form>
<a href="javascript:uploadExcle();" >上傳Excel</a>

js:

 function uploadExcle() {

  var file = $("#file").val();
  if (‘‘ == file) {
    alert("請選擇文件");
    return;
  }
  var fileType = (file.substring(file.lastIndexOf(".") + 1, file.length)).toLowerCase();
  if (fileType !== ‘xls‘ && fileType !== ‘xlsx‘) {
    alert(‘文件格式不正確,請選擇excel文件!‘);
    return;
  }

  //設置form表單提交URL,並提交
  var form = document.getElementById("excelFrom");
  form.action = "api/logistics/uploadExcle";
  document.getElementById("excelFrom").submit();
}

後臺導入的包:

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
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;

後臺代碼:

  

@RequestMapping(value="/uploadExcle")
public void uploadExcle(@RequestParam MultipartFile file) throws IOException{
  List<String[]> excelDate = getExcelData(file);
  for (int i = 0; i < excelDate.size(); i++) {
    String[] data = excelDate.get(i);

    // 獲取數據 保存數據庫
    System.out.println(data[0]);
  }
}

public List<String[]> getExcelData(MultipartFile file) throws IOException{
  checkFile(file);
  //獲得Workbook工作薄對象
  Workbook workbook = getWorkBook(file);
  //創建返回對象,把每行中的值作為一個數組,所有行作為一個集合返回
  List<String[]> list = new ArrayList<String[]>();
  if(workbook != null){
    for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
      //獲得當前sheet工作表
      Sheet sheet = workbook.getSheetAt(sheetNum);
      if(sheet == null){
        continue;
      }
      //獲得當前sheet的開始行
      int firstRowNum = sheet.getFirstRowNum();
      //獲得當前sheet的結束行
      int lastRowNum = sheet.getLastRowNum();
      //循環除了第一行的所有行
      for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){
        //獲得當前行
        Row row = sheet.getRow(rowNum);
        if(row == null){
          continue;
        }
        //獲得當前行的開始列
int firstCellNum = row.getFirstCellNum();
//獲得當前行的列數
int lastCellNum = row.getLastCellNum();
String[] cells = new String[row.getLastCellNum()];
//循環當前行
for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
cells[cellNum] = getCellValue(cell);
}
list.add(cells);
}
}
}
return list;
}


/**
* 檢查文件
* @param file
* @throws IOException
*/
public void checkFile(MultipartFile file) throws IOException{
//判斷文件是否存在
if(null == file){
log.error("文件不存在!");
System.out.println("文件不存在");
}
//獲得文件名
String fileName = file.getOriginalFilename();
//判斷文件是否是excel文件
if(!fileName.endsWith("xls") && !fileName.endsWith("xlsx")){
log.error(fileName + "不是excel文件");
System.out.println(fileName + " : 是不是excel文件");
}
}
public Workbook getWorkBook(MultipartFile file) {
//獲得文件名
String fileName = file.getOriginalFilename();
//創建Workbook工作薄對象,表示整個excel
Workbook workbook = null;
try {
//獲取excel文件的io流
InputStream is = file.getInputStream();
//根據文件後綴名不同(xls和xlsx)獲得不同的Workbook實現類對象
if(fileName.endsWith("xls")){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith("xlsx")){
//2007 及2007以上
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
log.info(e.getMessage());
}
return workbook;
}

public String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
//把數字當成String來讀,避免出現1讀成1.0的情況
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//判斷數據的類型
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //數字
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //字符串
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //公式
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //故障
cellValue = "非法字符";
break;
default:
cellValue = "未知類型";
break;
}
return cellValue;
}

excel上傳保存到數據庫 poi