最近在学习中遇到了excel的导入和导出操作,上网查了很长时间,没有一个特别适合小白的项目,因此自己做了一个简单的可以实现导入导出功能的项目,自己做了好长时间,特此记录一下,废话不多说,看代码。
1工程目录结构
2.在maven项目中导入相关的jar包依赖
commons-fileupload
commons-fileupload
1.3.1
org.apache.poi
poi-ooxml
3.10-FINAL
org.apache.poi
poi
3.10-FINAL
3.创建一个工具类Excelutils
package com.itheima.crm.utils;
import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
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.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.itheima.crm.pojo.ExcelBean;
public class ExcelUtils {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* 描述:获取IO流中的数据,组装成List>对象
* @param in,fileName
* @return
* @throws IOException
*/
public List> getBankListByExcel(InputStream in,String fileName) throws Exception{
List> list = null;
//创建Excel工作薄
Workbook work = this.getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null; //页数
Row row = null; //行数
Cell cell = null; //列数
list = new ArrayList>();
//遍历Excel中所有的sheet
for (int i = 0; i < work.getNumberOfSheets(); i++) {
sheet = work.getSheetAt(i);
if(sheet==null){continue;}
//遍历当前sheet中的所有行
for (int j = sheet.getFirstRowNum(); j <= sheet.getLastRowNum(); j++) {
row = sheet.getRow(j);
if(row==null||row.getFirstCellNum()==j){continue;}
//遍历所有的列
List
package com.itheima.crm.pojo;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
public class ExcelBean implements java.io.Serializable {
private String headTextName;//列头(标题)名
private String propertyName;//对应字段名
private Integer cols;//合并单元格数
private XSSFCellStyle cellStyle;
public ExcelBean(){
}
public ExcelBean(String headTextName, String propertyName){
this.headTextName = headTextName;
this.propertyName = propertyName;
}
public ExcelBean(String headTextName, String propertyName, Integer cols) {
super();
this.headTextName = headTextName;
this.propertyName = propertyName;
this.cols = cols;
}
public String getHeadTextName() {
return headTextName;
}
public void setHeadTextName(String headTextName) {
this.headTextName = headTextName;
}
public String getPropertyName() {
return propertyName;
}
public void setPropertyName(String propertyName) {
this.propertyName = propertyName;
}
public Integer getCols() {
return cols;
}
public void setCols(Integer cols) {
this.cols = cols;
}
public XSSFCellStyle getCellStyle() {
return cellStyle;
}
public void setCellStyle(XSSFCellStyle cellStyle) {
this.cellStyle = cellStyle;
}
}
5 PeopleServiceservice层方法
@Service
public interface PeopleService {
String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response);
XSSFWorkbook exportExcelInfo() throws Exception;
}
6PeopleServiceImpl方法
package com.itheima.crm.service.serviceImpl;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.itheima.crm.pojo.ExcelBean;
import com.itheima.crm.pojo.people;
import com.itheima.crm.service.PeopleService;
import com.itheima.crm.utils.ExcelUtils;
@Service
public class PeopleServiceImpl implements PeopleService{
@Autowired
private com.itheima.crm.mapper.peopleMapper peopleMapper;
public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response){
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("upfile");
if(file.isEmpty()){
try {
throw new Exception("文件不存在!");
} catch (Exception e) {
e.printStackTrace();
}
}
InputStream in =null;
try {
in = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
List> listob = null;
try {
listob = new ExcelUtils().getBankListByExcel(in,file.getOriginalFilename());
} catch (Exception e) {
e.printStackTrace();
}
//该处可调用service相应方法进行数据保存到数据库中,现只对数据输出
for (int i = 0; i < listob.size(); i++) {
List lo = listob.get(i);
people vo = new people();
people j = null;
try {
j = peopleMapper.selectByPrimaryKey(Integer.valueOf(String.valueOf(lo.get(0))));
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
System.out.println("没有新增");
}
vo.setId(Integer.valueOf(String.valueOf(lo.get(0))));
vo.setUserName(String.valueOf(lo.get(1)));
vo.setPassword(String.valueOf(lo.get(2)));
vo.setAge(Integer.valueOf(String.valueOf(lo.get(3))));
vo.setDate(Date.valueOf(String.valueOf(lo.get(4))));
if(j == null)
{
peopleMapper.insert(vo);
}
else
{
peopleMapper.updateByPrimaryKey(vo);
}
}
return "文件导入成功!";
}
public XSSFWorkbook exportExcelInfo() throws Exception {
List
}
6 peopleMapper方法
public interface peopleMapper {
int deleteByPrimaryKey(Integer id);
int insert(people record);
int insertSelective(people record);
people selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(people record);
int updateByPrimaryKey(people record);
List
7peopleMapper.xml方法
id, user_name, password, age, date
delete from people
where id = #{id,jdbcType=INTEGER}
insert into people (id, user_name, password,
age, date)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER}, #{date,jdbcType=DATE})
insert into people
id,
user_name,
password,
age,
date,
#{id,jdbcType=INTEGER},
#{userName,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR},
#{age,jdbcType=INTEGER},
#{date,jdbcType=DATE},
update people
user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
date = #{date,jdbcType=DATE},
where id = #{id,jdbcType=INTEGER}
update people
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER},
date = #{date,jdbcType=DATE}
where id = #{id,jdbcType=INTEGER}
8 ExcelController层实现方法
@Controller
@RequestMapping("/uploadExcel/*")
public class ExcelController {
@Autowired
private PeopleService peopleService;
/**
* 描述:通过 jquery.form.js 插件提供的ajax方式上传文件
* @param request
* @param response
* @throws Exception
*/
@ResponseBody
@RequestMapping(value="ajaxUpload.action",method={RequestMethod.GET,RequestMethod.POST})
public String ajaxUploadExcel(HttpServletRequest request,HttpServletResponse response) throws Exception {
return peopleService.ajaxUploadExcel(request, response);
}
@RequestMapping(value = "download.action")
public void export(HttpServletRequest request,HttpServletResponse response) throws Exception{
response.reset(); //清除buffer缓存
//Map map=new HashMap();
// 指定下载的文件名
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Content-Disposition","attachment;filename="+new String("用户表.xlsx".getBytes(),"iso-8859-1"));
//导出Excel对象
XSSFWorkbook workbook = peopleService.exportExcelInfo();
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.flush();
workbook.write(bufferedOutput);
bufferedOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
9 前段界面
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'index.jsp' starting page
1.通过简单的form表单提交方式,进行文件的上 2.通过jquery.form.js插件提供的form表单一步提交功能
10.功能结果实现图
前段界面
下载文件
|
11源代码获取
链接:https://pan.baidu.com/s/1tVdWU_TMGqoAUGuZfRpF9w
提取码:2rje
复制这段内容后打开百度网盘手机App,操作更方便哦
+++++++++++++++++++++=============================================
————————————————————————————————————_——————————————————————————————————————
Java后端小白一枚,有错误希望大家相互指出,共同进步。