Java中添加从Excel表格中导入数据和将数据导出到Excel表格并下载
jsp页面
总共需要添加四个按钮:
1.选择导入的Excel 文件按钮
2.上传按钮
3.关闭按钮
4.导出Excel文件按钮
上传文件时我利用了表单来导入,在用户点击上传按钮时触发tosubmit()方法,具体代码如下:
<li><a class="delete"
href="<c:url value='/management/peopleManager/downloadTemplate'/>"
onclick="downloadTemplate()"><span>导出Excel</span> </a>
</li>
<form id="importUserform" encType="multipart/form-data"
action="<c:url value='/***'/>" method="post">
<li>
<input id="excel_file" class="textinput" name="excel_file"
type="file" accept=".xls" />
</li>
<li>
<div class="buttonActive">
<div class="buttonContent">
<button type="button" onclick="tosubmit();">导入</button>
</div>
</div>
</li>
<li>
<div class="button">
<div class="buttonContent">
<button type="button" class="close">关闭</button>
</div>
</div>
</li>
如果觉得导入按钮的样式比较丑,可以设置它的style="display:none"来隐藏掉,然后另外写一个你喜欢的button,点击时触发其效果就可以。
function tosubmit(){
//进行表单验证
var excel_file = $("#excel_file").val();
if (excel_file == "" || excel_file.length == 0) {
alertMsg.info('请选择文件路径');
return false;
}
$('#importUserform').submit();
};
//下载Excel表格
function downloadTemplate() {
document.getElementById("keyTemplate").click();
}
Java
接下来,要导入poi的jar包,我将读取Excel文件内容的操作写成了一个工具类ReadExcelUtil,利用它来完成读取内容操作。
import com.ibm.icu.text.SimpleDateFormat;
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.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 工具类读取Excel类中内容
*/
public class ReadExcelUtil {
// 总行数
private int totalRows = 0;
// 总条数
private int totalCells = 0;
// 错误信息接收器
private String errorMsg;
// 构造方法
public ReadExcelUtil() {
}
// 获取总行数
public int getTotalRows() {
return totalRows;
}
// 获取总列数
public int getTotalCells() {
return totalCells;
}
// 获取错误信息-暂时未用到暂时留着
public String getErrorInfo() {
return errorMsg;
}
/**
* 从Excel表格中获取数据
* @param Mfile
* @param name
* @param request
* @return
*/
public List<?> getExcelInfo(MultipartFile Mfile, String name,
HttpServletRequest request) {
// 把spring文件上传的MultipartFile转换成CommonsMultipartFile类型
CommonsMultipartFile cf = (CommonsMultipartFile) Mfile; // 获取本地存储路径
// String path =
// request.getSession().getServletContext().getRealPath("/")
// + "upload/";
String path = "D:/upload/user/";
File file = new File(path);
// 创建一个目录 (它的路径名由当前 File 对象指定,包括任一必须的父路径。)
if (!file.exists())
file.mkdirs();
// 新建一个文件
File file1 = new File(path + name + DateTools.getServerDateTime(8)
+ ".xls");
// 将上传的文件写入新建的文件中
try {
cf.getFileItem().write(file1);
} catch (Exception e) {
e.printStackTrace();
}
// 初始化用户信息的集合
List<?> list = null;
// 初始化输入流
FileInputStream is = null;
Workbook wb = null;
try {
// 根据新建的文件实例化输入流
is = new FileInputStream(file1);
// 根据excel里面的内容读取客户信息
// 当excel是2003时
wb = new HSSFWorkbook(is);
// 当excel是2007时
// wb = new XSSFWorkbook(is);
list = new ArrayList<User>();
// 读取Excel里面客户的信息
list = readUserExcelValue(wb);
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
is = null;
e.printStackTrace();
}
}
}
return list;
}
/**
* 读取 Excel里面用户的信息
*
* @param wb
* @param accountType 人员类别
* @return
*/
private List<Weihu> readUserExcelValue(Workbook wb) {
// 得到第一个shell
Sheet sheet = wb.getSheetAt(0);
// 得到Excel的行数
this.totalRows = sheet.getPhysicalNumberOfRows();
// 得到Excel的列数(前提是有行数)
// 判断行数大于一,并且第一行必须有标题(这里有bug若文件第一行没值就完了)
if (totalRows >= 1 && sheet.getRow(0) != null) {
this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
} else {
return null;
}
// 声明一个对象集合
List<Weihu> weihuList = new ArrayList<Weihu>();
// 声明一个对象
Weihu weihu = new Weihu();
String name = "";
String mobilephone = "";
String deptname = "";
String position = "";
Row titles = sheet.getRow(0);
//判断表格的形式是否符合
if (!((getValue(titles.getCell(0)).equals("姓名") || getValue(titles.getCell(0)).equals("名字"))
&& (getValue(titles.getCell(1)).equals("手机号码") || getValue(titles.getCell(1)).equals("手机号") || getValue(titles.getCell(1)).equals("手机"))
&& getValue(titles.getCell(2)).equals("部门"))
&& (getValue(titles.getCell(3)).equals("职位") || getValue(titles.getCell(3)).equals("职务"))) {
return null;
}
// 循环Excel行数,从第二行开始。标题不入库
for (int r = 1; r < totalRows; r++) {
Row row = sheet.getRow(r);
if (row == null)
continue;
weihu = new Weihu();
// 循环Excel的列
for (int c = 0; c < this.totalCells; c++) {
Cell cell = row.getCell(c);
if (null != cell) {
if (c == 0) {
name = getValue(cell);// 得到行中第一个值
weihu.setName(name);
} else if (c == 1) {
mobilephone = getValue(cell);// 得到行中第二个值
weihu.setMobilephone(mobilephone);
} else if (c == 2) {
deptname = getValue(cell);// 得到行中第三个值
weihu.setDeptname(deptname);
} else if (c == 3) {
position = getValue(cell);// 得到行中第四个值
weihu.setPosition(position);
}
}
}
weihuList.add(weihu);
}
return weihuList;
}
代码逻辑:
//导入Excel
@RequestMapping(value = "/importUser", method = RequestMethod.POST)
public ModelAndView importUser(@RequestParam(value = "excel_file") MultipartFile file,
HttpServletRequest request, HttpServletResponse response){
//判断上传文件是否为空
if (file == null) {
return ajaxDoneError("文件为空!");
}
// 获取文件名
String name = file.getOriginalFilename();
// 进一步判断文件是否为空(即判断其大小是否为0或其名称是否为null)验证文件名是否合格
long size = file.getSize();
if (null == name || ("").equals(name) && size == 0) {
return ajaxDoneError("文件格式错误!");
}
// 创建处理Excel
ReadExcelUtil readExcel = new ReadExcelUtil();
// 解析Excel,获取客户信息集合
List<Weihu> userList = (List<Weihu>) readExcel.getExcelInfo(file, name, request);
if (userList != null && !weihuList.toString().equals("[]")
&& userList.size() >= 1) {
//遍历list
for (User user : userList) {
//向数据库添加人员数据
userMapper.insertSelective(user);
}
} else {
return ajaxDoneError("文件格式错误!请仔细检查文件内容,标题等是否与模板一致。");
}
ModelAndView mv = new ModelAndView("redirect:/*");
return mv;
}
//导出Excel
@RequestMapping("/downloadTemplate")
public void setUpExcel (HttpServletRequest request, HttpServletResponse response) throws IOException{
//设置Excel表格每一栏的标题
String[] headers = { "姓名", "手机号码","部门","职位"};
//创建查询条件
UserExample example = new UserExample();
Criteria criteria = example.createCriteria();
//执行查询
List<User> userList = userMapper.selectByExample(example);
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
//设置列宽
sheet.setDefaultColumnWidth((short) 18);
//创建第一行的对象,第一行一般用于填充标题内容。从第二行开始一般是数据
HSSFRow row = sheet.createRow(0);
for (short i = 0; i < headers.length; i++) {
//创建单元格,每行多少数据就创建多少个单元格
HSSFCell cell = row.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
//给单元格设置内容
cell.setCellValue(text);
}
//遍历集合,将每个集合元素对象的每个值填充到单元格中
for(int i = 0;i < userList.size(); i++){
User User = userList.get(i);
//从第二行开始填充数据
row = sheet.createRow(i+1);
List<String> datas = new ArrayList<String>();
//将数据设置到datas中
datas.add(user.getName());
datas.add(user.getMobilephone());
datas.add(user.getDeptname());
datas.add(user.getPosition());
//遍历datas
for (int j=0; j < datas.size(); j++) {
//为单元格中填充数据
String string=datas.get(j);
HSSFCell cell = row.createCell(j);
HSSFRichTextString richString = new HSSFRichTextString(string);
HSSFFont font3 = workbook.createFont();
//定义Excel数据颜色,这里设置为蓝色
font3.setColor(HSSFColor.BLUE.index);
richString.applyFont(font3);
cell.setCellValue(richString);
}
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename="+"user-template.xls");//Excel文件名
try {
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
//将workbook中的内容写入输出流中
workbook.write(response.getOutputStream());
}
以上,解决问题。