java匯入excel
阿新 • • 發佈:2018-12-31
匯入excel
layui框架
要匯入的表格是有規則的 如:
HTML
<a style="margin-right:11px" class="layui-btn layui-btn-primary" id="uploadExcel"><i class="layui-icon"></i>匯入學生</a>
js
upload.render({ //允許上傳的檔案字尾
elem: '#uploadExcel',
url: 'student/uploadExcel.do' ,
accept: 'file', //普通檔案
ext : 'xls|xlsx',
title : '請選擇Excel檔案',
before: function(obj){ //obj引數包含的資訊,跟 choose回撥完全一致,可參見上文。
layer.load(); //上傳loading
},
done: function(res, index, upload){
layer.closeAll('loading' ); //關閉loading
if(res.code == 1){
`這裡寫程式碼片`top.layer.msg(res.msg, {icon: 6});
}else{
top.layer.msg(res.msg, {icon: 5});
}
},
error: function(){
//請求異常回調
}
});
控制層
@ControllerOptLog(desc="匯入")
@RequestMapping(value = "uploadExcel")
@ResponseBody
public JsonBean uploadExcel(@RequestParam MultipartFile file) throws IOException {
return studentService.insertExcelToDB(file);
}
業務層
@SuppressWarnings("finally")
@Override
public JsonBean insertExcelToDB(MultipartFile file) {
//JsonBean 封裝的物件
JsonBean jsonBean = new JsonBean(0, "Excel匯入失敗!", null);
//讀取Excel資料到List中
try {
List<ArrayList<String>> list = new ExcelRead().readExcel(file);
//list中存的就是excel中的資料,可以根據excel中每一列的值轉換成你所需要的值(從0開始)
Student student = null;
List<Student> liseStudent = new ArrayList<Student>();
for(ArrayList<String> arr : list){
//按照表格的規則迴圈新增
if(arr.get(0)!=null&&!arr.get(0).toString().equals("")){
student = new Student();
student.setName(arr.get(0).toString());
if(arr.get(1).toString().equals("男")){
student.setSex("1");
}else if(arr.get(1).toString().equals("女")){
student.setSex("0");
}
student.setBirthday(arr.get(2));
student.setAddress(arr.get(3).toString());
student.setFather_name(arr.get(4).toString());
student.setFather_phone(arr.get(5).toString());
student.setMather_name(arr.get(6).toString());
student.setMather_phone(arr.get(7).toString());
student.setPhone(arr.get(8).toString());
student.setEducation(arr.get(9).toString());
student.setAdd_time(arr.get(10));
student.setStatus(arr.get(11).toString());
student.setClassnum(arr.get(12).toString());
student.setAccommodation(Integer.valueOf(arr.get(13).toString()));
student.setRemake(arr.get(14).toString());
liseStudent.add(student);
}
}
int i = studentMapper.insertStudentList(liseStudent);
if(i>0){
jsonBean = new JsonBean(1, "Excel匯入成功!", null);
}
} catch (Exception e) {
jsonBean = new JsonBean(0, "請檢視Excel格式是否正確!", null);
e.printStackTrace();
} finally{
return jsonBean;
}
}
下面就是匯入要用到的工具類了
package xxx.xxx.xxx.utils;
public class ExcelRead {
public int totalRows; //sheet中總行數
public static int totalCells; //每一行總單元格數
/**
* read the Excel .xlsx,.xls
* @param file jsp中的上傳檔案
* @return
* @throws IOException
*/
public List<ArrayList<String>> readExcel(MultipartFile file) throws IOException {
if(file==null||ExcelUtil.EMPTY.equals(file.getOriginalFilename().trim())){
return null;
}else{
String postfix = ExcelUtil.getPostfix(file.getOriginalFilename());
if(!ExcelUtil.EMPTY.equals(postfix)){
if(ExcelUtil.OFFICE_EXCEL_2003_POSTFIX.equals(postfix)){
return readXls(file);
}else if(ExcelUtil.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)){
return readXlsx(file);
}else{
return null;
}
}
}
return null;
}
/**
* read the Excel 2010 .xlsx
* @param file
* @param beanclazz
* @param titleExist
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXlsx(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流讀取檔案
InputStream input = null;
XSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 建立文件
wb = new XSSFWorkbook(input);
//讀取sheet(頁)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
XSSFSheet xssfSheet = wb.getSheetAt(numSheet);
if(xssfSheet == null){
continue;
}
totalRows = xssfSheet.getLastRowNum();
//讀取Row,從第二行開始
for(int rowNum = 1;rowNum <= totalRows;rowNum++){
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if(xssfRow!=null){
rowList = new ArrayList<String>();
totalCells = xssfRow.getLastCellNum();
//讀取列,從第一列開始
for(int c=0;c<=totalCells+1;c++){
XSSFCell cell = xssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getXValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* read the Excel 2003-2007 .xls
* @param file
* @param beanclazz
* @param titleExist
* @return
* @throws IOException
*/
public List<ArrayList<String>> readXls(MultipartFile file){
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
// IO流讀取檔案
InputStream input = null;
HSSFWorkbook wb = null;
ArrayList<String> rowList = null;
try {
input = file.getInputStream();
// 建立文件
wb = new HSSFWorkbook(input);
//讀取sheet(頁)
for(int numSheet=0;numSheet<wb.getNumberOfSheets();numSheet++){
HSSFSheet hssfSheet = wb.getSheetAt(numSheet);
if(hssfSheet == null){
continue;
}
totalRows = hssfSheet.getLastRowNum();
//讀取Row,從第二行開始
for(int rowNum = 1;rowNum <= totalRows;rowNum++){
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if(hssfRow!=null){
rowList = new ArrayList<String>();
totalCells = hssfRow.getLastCellNum();
//讀取列,從第一列開始
for(short c=0;c<=totalCells+1;c++){
HSSFCell cell = hssfRow.getCell(c);
if(cell==null){
rowList.add(ExcelUtil.EMPTY);
continue;
}
rowList.add(ExcelUtil.getHValue(cell).trim());
}
list.add(rowList);
}
}
}
return list;
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
package xxx.xxx.xxx.utils;
public class ExcelUtil {
public static final String OFFICE_EXCEL_2003_POSTFIX = "xls";
public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";
public static final String EMPTY = "";
public static final String POINT = ".";
public static SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
/**
* 獲得path的字尾名
* @param path
* @return
*/
public static String getPostfix(String path){
if(path==null || EMPTY.equals(path.trim())){
return EMPTY;
}
if(path.contains(POINT)){
return path.substring(path.lastIndexOf(POINT)+1,path.length());
}
return EMPTY;
}
/**
* 單元格格式
* @param hssfCell
* @return
*/
@SuppressWarnings({ "static-access", "deprecation" })
public static String getHValue(HSSFCell hssfCell){
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if(HSSFDateUtil.isCellDateFormatted(hssfCell)){
Date date = HSSFDateUtil.getJavaDate(hssfCell.getNumericCellValue());
cellValue = sdf.format(date);
}else{
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(hssfCell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
if(strArr.equals("00")){
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
return String.valueOf(hssfCell.getStringCellValue());
}
}
/**
* 單元格格式
* @param xssfCell
* @return
*/
public static String getXValue(XSSFCell xssfCell){
if (xssfCell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfCell.getBooleanCellValue());
} else if (xssfCell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if(XSSFDateUtil.isCellDateFormatted(xssfCell)){
Date date = XSSFDateUtil.getJavaDate(xssfCell.getNumericCellValue());
cellValue = sdf.format(date);
}else{
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(xssfCell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
if(strArr.equals("00")){
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
return String.valueOf(xssfCell.getStringCellValue());
}
}
static class XSSFDateUtil extends DateUtil{
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
}
}
另外這是我的第二篇部落格