1. 程式人生 > >excel資料匯入ssm

excel資料匯入ssm

java web專案匯入excel資料,是實用頻率非常高的功能,通過做了幾個這樣的功能之後,現將此功能總結出了,對於Excel表的結構,簡單理解我覺得大體可以把它分成三部分(SheetCellRow),可以把這三部分理解為,為了以後自己方便使用,也為大家實現此功能做一個參考.

1.匯入對應的jar包

2.Excel讀取工具類

package org.springmvc.util;
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.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


/**
 * Excel讀取工具類
 */
public class ExcelUtil {
    private final static String excel2003L = ".xls";
    private final static String excel2007U = ".xlsx";


    //讀取檔案資料
    public static List<List<Object>> getExcelList(InputStream is, String fileName) throws Exception{
        List<List<Object>> list = new ArrayList<List<Object>>();
        Workbook workbook = null;


        //驗證檔案格式
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        if(suffix.equals(excel2003L)){
            workbook = new HSSFWorkbook(is);
        }else if(suffix.equals(excel2007U)){
            workbook = new XSSFWorkbook(is);
        }


        Sheet sheet = null;
        Row row = null;
        Cell cell = null;


        for(int i = 0 ; i < workbook.getNumberOfSheets();i++){
            sheet = workbook.getSheetAt(i);
            if(sheet == null) continue;
            //遍歷當前sheet中全部行
            for(int j = sheet.getFirstRowNum();j < sheet.getLastRowNum();j++){
                row = sheet.getRow(j);
                if(row == null) continue;
                //迴圈當前row中全部列
                List<Object> li = new ArrayList<Object>();
                for (int k = row.getFirstCellNum();k < row.getLastCellNum();k++){
                    cell = row.getCell(k);
                    if(cell!=null){
                        li.add(getCellValue(cell));
                    }
                }
                list.add(li);
            }
        }


        return list;
    }


    //單元格資料型別格式化
    public static Object getCellValue(Cell cell){
        Object value = null;
        DecimalFormat decimalFormat1 = new DecimalFormat("0");
        DecimalFormat decimalFormat2 = new DecimalFormat("0.00");
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");


        switch (cell.getCellType()){
            case Cell.CELL_TYPE_NUMERIC:
                if("General".equals(cell.getCellStyle().getDataFormatString())){
                    value = decimalFormat1.format(cell.getNumericCellValue());
                }else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
                    value = dateFormat.format(cell.getDateCellValue());
                }else{
                    value = decimalFormat2.format(cell.getNumericCellValue());
                }
                break;
            case Cell.CELL_TYPE_BOOLEAN:
                value = cell.getBooleanCellValue();
                break;
            case Cell.CELL_TYPE_BLANK:
                value = "";
                break;
            case Cell.CELL_TYPE_STRING:
                value = cell.getStringCellValue();
                break;
        }
        return value;
    }
}


  3.Controller頁面
//通過模態框顯示批量新增頁面
@RequestMapping(value="/batchAdd",method=RequestMethod.GET)
public String batchAdd(){
return "blog/batchAdd";
}
//批量匯入Excel資料到資料庫
@RequestMapping(value="/batchAdd",method=RequestMethod.POST)
@ResponseBody
public String batchAdd(MultipartHttpServletRequest multipartHttpServletRequest) throws IOException, Exception{
int count = 0;//匯入總條數
MultipartFile file = multipartHttpServletRequest.getFile("uploadXls");
List<List<Object>> list = ExcelUtil.getExcelList(file.getInputStream(), file.getOriginalFilename());
count = list.size();
//title,content,author,createtime,category_id,pic
for (int i = 0; i < list.size(); i++) {
List<Object> lo = list.get(i);
Blog b = new Blog();
b.setTitle(lo.get(0).toString());
b.setContent(lo.get(1).toString());
b.setAuthor(lo.get(2).toString());
b.setIssueDate(new SimpleDateFormat("yyyy/MM/dd").parse(lo.get(3).toString()));
Category c = new Category();
c.setId(Integer.parseInt(lo.get(4).toString()));
b.setCategory(c);
b.setMypic(lo.get(5).toString());
blogDao.insert(b);

for(int j = 0;j<lo.size();j++){
Object o = list.get(i).get(j);
System.out.print(o+"\t\t");
}
System.out.println();
}
return String.format("資料匯入成功!共計%s條", count);
}


4.jsp頁面
1.<button class="btn btn-warning" onclick="showDialog('#myModal','批量新增部落格','blog/batchAdd')"><i class="glyphicon glyphicon-add"></i>批量匯入</button>
<!--在form標籤下新增一個屬性,enctype="multipart/form-data"-->
2.<form class="form" action="blog/batchAdd" method="post" enctype="multipart/form-data">
        <input class="form-control" type="file" name="uploadXls" id="uploadXls">
</form>
function submitForm(){
var $form = $modal.find('form');
var action = $form.attr('action');
//檔案上傳提交表單需要如下程式碼
//FormData html5新新增的屬性 ,可以支援檔案上傳
//FormData 在ie8中不支援,  jquery.form.js
//new FormData(dom)
//jquery-->dom  $form.get(0);  $form[0]
//dom-->jquery  $(dom)
var form = new FormData($form.get(0));
$.ajax({
url:action,
type:'post',
data:form,
async: false,
        cache: false,
        contentType: false,
        processData: false,
success:function(data){
$modal.modal('hide');
bootstrapTable.bootstrapTable('refresh');
}
});
}
//批量新增
function batchAdd(modal,url){

}