做Excel导入和导出,不算是第一次,但是,实现从前台到后台一条线的流程,这次算是全部知道了。接下来吧憋了这几天的成果告诉大家。现在贴上参照博主的链接点击打开链接。
首先准备jar包,
创建ExcelUtil类 代码如下:
package com.bluemobi.util;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
/**
* Excel工具类
* @author lp
*
*/
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());
}
}
}
/**
* 自定义xssf日期工具类
*
* @author lp
*/
class XSSFDateUtil extends DateUtil {
protected static int absoluteDay(Calendar cal, boolean use1904windowing) {
return DateUtil.absoluteDay(cal, use1904windowing);
}
public static void main(String[] args) throws IOException {
}
}
创建ExcelRead类,用于读取Excel表格中的内容
package com.bluemobi.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
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
*/
@SuppressWarnings("deprecation")
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;
}
}
基本的Excel读取类做完了之后就开始看前台和后台的联合
1、jsp中的写法
jsp需要接收一个文件,并且放到form表单中,随着表单提交。所以代码如下
<form method="post" action="#" enctype="multipart/form-data" id="upload">
<input type="file" class="one" name="myfile"id="myfile" style="float: left;margin-top: 5px;">
<input type="button" class="btn btn-sm btn-default" value="上传" style="float: left" id="ajaxSubmit" οnclick="importExcel()">
</form>
2、js中的代码
function importExcel(){
$("#upload").ajaxSubmit({
type:'post',
url:你自己的controller中的url,
success:function(data){
if (data.status == 0) {
if(data.data != 0){
layer.msg('此表单已存在且正在使用中!');
//window.location.reload();
}else{
layer.msg(data.msg, {icon: 1});
window.location.reload();
}
} else {
layer.msg(data.msg, {icon: 1});
window.location.reload();
}
},
error:function(XmlHttpRequest,textStatus,errorThrown){
console.log(XmlHttpRequest);
console.log(textStatus);
console.log(errorThrown);
}
});
3、controller中的代码
//导入Excel
@RequestMapping(value="importExcel", method = RequestMethod.POST)
@ResponseBody
public ModelAndView importExcel(@RequestParam("myfile") MultipartFile file) throws IOException {
ModelAndView mv = new ModelAndView();
//判断文件是否为空
if(file == null){
mv.addObject("msg", "failed");
mv.setViewName("excel_result");
return mv;
}
String name = file.getOriginalFilename();
long size = file.getSize();
if(name == null || ExcelUtil.EMPTY.equals(name) && size==0){
mv.addObject("msg", "failed");
mv.setViewName("excel_result");
return mv;
}
//读取Excel数据到List中
List<ArrayList<String>> list = new ExcelRead().readExcel(file);
//list中存的就是excel中的数据,可以根据excel中每一列的值转换成你所需要的值(从0开始),如:
实体 实体1= null;
List<ZkResourse> zkResourseList = new ArrayList<ZkResourse>();
// String[] strArrayTrue = (String[]) list.toArray(new String[0]);
Date nowdate=new Date();
for(ArrayList<String> arr:list){
实体 实体1= new 实体();
实体.set字段(arr.get(0));//从Excel中获取第一个单元格中的内容
list.add(实体);
}
if(service.importExcel(list)){
mv.addObject("msg", "success");
}else{
mv.addObject("msg", "failed");
}
mv.setViewName("excel_result");
return mv;
}
接下来的后台 importExcel是一个批量插入数据库的过程,如要了解,请见下回分析。