您的位置:首页 > 编程语言 > Java开发

Java上传Excel文件导入数据

2017-08-31 21:52 501 查看
Controller中接收form表单提交的文件域:

public Map importConsumer(@RequestParam("file") MultipartFile file)

读取Excel工具类 这里我以Consumer实体类来写,大家可以自行封装:

public class ReadExcel
{
// 总行数
private int totalRows = 0;
// 总条数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg;

// 构造方法
public ReadExcel()
{
}

// 获取总行数
public int getTotalRows()
{
return totalRows;
}

// 获取总列数
public int getTotalCells()
{
return totalCells;
}

// 获取错误信息
public String getErrorInfo()
{
return errorMsg;
}

/**
* 验证EXCEL文件
*
* @param filePath
* @return
*/
public boolean validateExcel(String filePath)
{
if(filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath)))
{
errorMsg = "文件名不是excel格式";
return false;
}
return true;
}

/**
* 读EXCEL文件,获取客户信息集合
*
* @param fielName
* @return
*/
public List<Consumer> getExcelInfo(String fileName, MultipartFile Mfile)
{

// 把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; // 获取本地存储路径
File file = new File("D:\\fileupload");
// 创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
if(!file.exists())
file.mkdirs();
// 新建一个文件
File file1 = new File("D:\\fileupload" + new Date().getTime() + ".xlsx");
// 将上传的文件写入新建的文件中
try
{
cf.getFileItem().write(file1);
}
catch (Exception e)
{
e.printStackTrace();
}

// 初始化客户信息的集合
List<Consumer> customerList = new ArrayList<Consumer>();
// 初始化输入流
InputStream is = null;
try
{
// 验证文件名是否合格
if(!validateExcel(fileName))
{
return null;
}
// 根据文件名判断文件是2003版本还是2007版本
boolean isExcel2003 = true;
if(WDWUtil.isExcel2007(fileName))
{
isExcel2003 = false;
}
// 根据新建的文件实例化输入流
is = new FileInputStream(file1);
// 根据excel里面的内容读取客户信息
customerList = getExcelInfo(is, isExcel2003);
is.close();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if(is != null)
{
try
{
is.close();
}
catch (IOException e)
{
is = null;
e.printStackTrace();
}
}
}
return customerList;
}

/**
* 根据excel里面的内容读取客户信息
*
* @param is
* 输入流
* @param isExcel2003
* excel是2003还是2007版本
* @return
* @throws IOException
*/
public List<Consumer> getExcelInfo(InputStream is, boolean isExcel2003)
{
List<Consumer> customerList = null;
try
{
/** 根据版本选择创建Workbook的方式 */
Workbook wb = null;
// 当excel是2003时
if(isExcel2003)
{
wb = new HSSFWorkbook(is);
}
else
{// 当excel是2007时
wb = new XSSFWorkbook(is);
}
// 读取Excel里面客户的信息
customerList = readExcelValue(wb);
}
catch (IOException e)
{
e.printStackTrace();
}
return customerList;
}

/**
* 读取Excel里面客户的信息
* @param wb
* @return
*/
private List<Consumer> readExcelValue(Workbook wb){
//得到第一个shell
Sheet sheet=wb.getSheetAt(0);

//得到Excel的行数
this.totalRows=sheet.getPhysicalNumberOfRows();

//得到Excel的列数(前提是有行数)
if(totalRows>=1 && sheet.getRow(0) != null){
this.totalCells=sheet.getRow(0).getPhysicalNumberOfCells();
}

List<Consumer> customerList=new ArrayList<Consumer>();
Consumer consumer;
//循环Excel行数,从第二行开始。标题不入库
for(int r=1;r<totalRows;r++){
Row row = sheet.getRow(r);
if (row == null) continue;
consumer = new Consumer();

//循环Excel的列
for(int c = 0; c <this.totalCells; c++){
Cell cell = row.getCell(c);
cell.setCellType(CellType.STRING);
if(null != cell)
{
if(c == 0)
{
consumer.setName(cell.getStringCellValue()); // 姓名
}
else if(c == 1)
{
consumer.setPhone(cell.getStringCellValue()); // 手机号码
}
else if(c == 2)
{
consumer.setEmail(cell.getStringCellValue()); // 客户简称
}
else if(c == 3)
{
consumer.setCreateUserId(cell.getStringCellValue()); //所属访员账号
}
}
}
//添加客户
customerList.add(consumer);
}
return customerList;
}
}Service里面调用:
public Map importConsumer(MultipartFile file,Users currentUser)
{
Map<String, Object> map = new HashMap<String, Object>();

boolean b = false;
// 创建处理EXCEL
ReadExcel readExcel = new ReadExcel();
// 解析excel,获取客户信息集合。
List<Consumer> ConsumerList = readExcel.getExcelInfo(file.getOriginalFilename(), file);

if(ConsumerList != null)
{
b = true;
map.put("code", 0);
}
else
{
map.put("code", -1);
}
map.put("msg", "");

for(Consumer consumer:ConsumerList)
{
String guid = java.util.UUID.randomUUID().toString();
consumer.setId(guid);
consumer.setCompanyId(currentUser.getCompanyId());
consumer.setCreateTime(formatter.format(new Date()));
consumerDao.insert(consumer); //或者进行批量保存
}
return map;
}
注意会出现异常:java.lang.NoClassDefFoundError: org/apache/commons/collections4/ListValuedMap

这是缺少jar包,需要下载commons-collections4-4.1.jar,然后放在lib下面,build path 加入到项目里面去.

cell.getStringCellValue()这句代码也可能报异常,获取单元格的数据都为String类型,单元格的数据还可能是其他类型数据,
循环excel列需要设置一下都转成String类型,row.getCell(0).setCellType(CellType.STRING);

基础代码,大家需要自行扩展。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: