对于批量数据的操作,在项目中引进Excel的导入和导出功能是个不错的选择。对于Excel表的结构,简单理解我觉得大体可以把它分成三部分(Sheet,Cell,Row),可以把这三部分理解为页,列,行。因此,我们想要获取到某一个单元的内容,可以通过获取该单元所在的页数和对应所在的行和列从而定位到该单位,继而便可执行操作从而获取其中的内容。Java使用POI实现对excel的导入和导出也是相似的思路。
环境,导入POI对应的包
spring+springMVC+Mybatis
<!-- JXL -->
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.16</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.16</version>
</dependency>
创建一个ExcelBean实现数据的封装
package com.heitian.ssm.test;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
/**
* Created by benhailong on 2017/9/18.
*/
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;
}
/* 省略了get和set方法 */
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;
}
}
创建一个Excel表数据导入和导出的工具类ExcelUtil
package com.heitian.ssm.util;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.heitian.ssm.test.ExcelBean;
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.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
/** Excel导入导出工具类
* Created by benhailong on 2017/9/18.
*/
public class ExcelUtil {
private final static String excel2003L =".xls"; //2003- 版本的excel
private final static String excel2007U =".xlsx"; //2007+ 版本的excel
/**
* Excel导入
*/
public static List<List<Object>> getBankListByExcel(InputStream in, String fileName) throws Exception{
List<List<Object>> list = null;
//创建Excel工作薄
Workbook work = getWorkbook(in,fileName);
if(null == work){
throw new Exception("创建Excel工作薄为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
list = new ArrayList<List<Object>>();
//遍历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<Object> li = new ArrayList<Object>();
for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
li.add(getCellValue(cell));
}
list.add(li);
}
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
*/
public static Workbook getWorkbook(InputStream inStr,String fileName) throws Exception{
Workbook wb = null;
String fileType = fileName.substring(fileName.lastIndexOf("."));
if(excel2003L.equals(fileType)){
wb = new HSSFWorkbook(inStr); //2003-
}else if(excel2007U.equals(fileType)){
wb = new XSSFWorkbook(inStr); //2007+
}else{
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
*/
public static Object getCellValue(Cell cell){
Object value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化字符类型的数字
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
value = cell.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if("General".equals(cell.getCellStyle().getDataFormatString())){
value = df.format(cell.getNumericCellValue());
}else if("m/d/yy".equals(cell.getCellStyle().getDataFormatString())){
value = sdf.format(cell.getDateCellValue());
}else{
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
break;
}
return value;
}
/**
* 导入Excel表结束
* 导出Excel表开始
* @param sheetName 工作簿名称
* @param clazz 数据源model类型
* @param objs excel标题列以及对应model字段名
* @param map 标题列行数以及cell字体样式
*/
public static XSSFWorkbook createExcelFile(Class clazz, List objs, Map<Integer, List<ExcelBean>> map, String sheetName) throws
IllegalArgumentException,IllegalAccessException,InvocationTargetException,
ClassNotFoundException, IntrospectionException, ParseException {
// 创建新的Excel工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值, 也可以指定Sheet名称
XSSFSheet sheet = workbook.createSheet(sheetName);
// 以下为excel的字体样式以及excel的标题与内容的创建,下面会具体分析;
createFont(workbook); //字体样式
createTableHeader(sheet, map); //创建标题(头)
createTableRows(sheet, map, objs, clazz); //创建内容
return workbook;
}
private static XSSFCellStyle fontStyle;
private static XSSFCellStyle fontStyle2;
public static void createFont(XSSFWorkbook workbook) {
// 表头
fontStyle = workbook.createCellStyle();
XSSFFont font1 = workbook.createFont();
font1.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font1.setFontName("黑体");
font1.setFontHeightInPoints((short) 14);// 设置字体大小
fontStyle.setFont(font1);
fontStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
fontStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
fontStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
fontStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
fontStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
// 内容
fontStyle2=workbook.createCellStyle();
XSSFFont font2 = workbook.createFont();
font2.setFontName("宋体");
font2.setFontHeightInPoints((short) 10);// 设置字体大小
fontStyle2.setFont(font2);
fontStyle2.setBorderBottom(XSSFCellStyle.BORDER_THIN); // 下边框
fontStyle2.setBorderLeft(XSSFCellStyle.BORDER_THIN);// 左边框
fontStyle2.setBorderTop(XSSFCellStyle.BORDER_THIN);// 上边框
fontStyle2.setBorderRight(XSSFCellStyle.BORDER_THIN);// 右边框
fontStyle2.setAlignment(XSSFCellStyle.ALIGN_CENTER); // 居中
}
/**
* 根据ExcelMapping 生成列头(多行列头)
*
* @param sheet 工作簿
* @param map 每行每个单元格对应的列头信息
*/
public static final void createTableHeader(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map) {
int startIndex=0;//cell起始位置
int endIndex=0;//cell终止位置
for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
XSSFRow row = sheet.createRow(entry.getKey());
List<ExcelBean> excels = entry.getValue();
for (int x = 0; x < excels.size(); x++) {
//合并单元格
if(excels.get(x).getCols()>1){
if(x==0){
endIndex+=excels.get(x).getCols()-1;
CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
sheet.addMergedRegion(range);
startIndex+=excels.get(x).getCols();
}else{
endIndex+=excels.get(x).getCols();
CellRangeAddress range=new CellRangeAddress(0,0,startIndex,endIndex);
sheet.addMergedRegion(range);
startIndex+=excels.get(x).getCols();
}
XSSFCell cell = row.createCell(startIndex-excels.get(x).getCols());
cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
if (excels.get(x).getCellStyle() != null) {
cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
}
cell.setCellStyle(fontStyle);
}else{
XSSFCell cell = row.createCell(x);
cell.setCellValue(excels.get(x).getHeadTextName());// 设置内容
if (excels.get(x).getCellStyle() != null) {
cell.setCellStyle(excels.get(x).getCellStyle());// 设置格式
}
cell.setCellStyle(fontStyle);
}
}
}
}
public static void createTableRows(XSSFSheet sheet, Map<Integer, List<ExcelBean>> map, List objs, Class clazz)
throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, IntrospectionException,
ClassNotFoundException, ParseException {
int rowindex = map.size();
int maxKey = 0;
List<ExcelBean> ems = new ArrayList<ExcelBean>();
for (Map.Entry<Integer, List<ExcelBean>> entry : map.entrySet()) {
if (entry.getKey() > maxKey) {
maxKey = entry.getKey();
}
}
ems = map.get(maxKey);
List<Integer> widths = new ArrayList<Integer>(ems.size());
for (Object obj : objs) {
XSSFRow row = sheet.createRow(rowindex);
for (int i = 0; i < ems.size(); i++) {
ExcelBean em = (ExcelBean) ems.get(i);
// 获得get方法
PropertyDescriptor pd = new PropertyDescriptor(em.getPropertyName(), clazz);
Method getMethod = pd.getReadMethod();
Object rtn = getMethod.invoke(obj);
String value = "";
// 如果是日期类型进行转换
if (rtn != null) {
if (rtn instanceof Date) {
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
// value = dateUtil.dateToString((Date)rtn);
value = sdf.format((Date)rtn);
} else if(rtn instanceof BigDecimal){
NumberFormat nf = new DecimalFormat("#,##0.00");
value=nf.format((BigDecimal)rtn).toString();
} else if((rtn instanceof Integer) && (Integer.valueOf(rtn.toString())<0 )){
value="--";
}else {
value = rtn.toString();
}
}
XSSFCell cell = row.createCell(i);
cell.setCellValue(value);
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
cell.setCellStyle(fontStyle2);
// 获得最大列宽
int width = value.getBytes().length * 300;
// 还未设置,设置当前
if (widths.size() <= i) {
widths.add(width);
continue;
}
// 比原来大,更新数据
if (width > widths.get(i)) {
widths.set(i, width);
}
}
rowindex++;
}
// 设置列宽
for (int index = 0; index < widths.size(); index++) {
Integer width = widths.get(index);
width = width < 2500 ? 2500 : width + 300;
width = width > 10000 ? 10000 + 300 : width + 300;
sheet.setColumnWidth(index, width);
}
}
}
Excel表导入Controller端实现
/**
* excelAvdSet 导入 Excel
*/
@RequestMapping("/excelAvdSet.do")
public String excelAvdSet(HttpServletRequest request,MultipartFile file) throws Exception {
log.info("这里是excelAvdSet.do, 导入 Excel");
//获取上传的文件
// MultipartHttpServletRequest multipart = (MultipartHttpServletRequest)request;
// MultipartFile file = multipart.getFile("file");
InputStream in = file.getInputStream();
//数据导入
advertisingService.importExcelInfo(in,file);
in.close();
return "login";
}
写一个 jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/advertising/excelAvdSet.do" method="post" enctype="multipart/form-data">
请选择Excel:<input type="file" name="file">
<input type="submit" name="提交">
</form>
</body>
</html>
Service层,这里是Service接口importExcellnfo的实现方法,调用了ExcelUtil里的方法
/**
* 导入
* @param in
* @param file
* @throws Exception
*/
public void importExcelInfo(InputStream in, MultipartFile file) throws Exception{
List<List<Object>> listob = ExcelUtil.getBankListByExcel(in,file.getOriginalFilename());
List<Advertising> advertisingList = new ArrayList<Advertising>();
//遍历listob数据,把数据放到List中
for (int i = 0; i < listob.size(); i++) {
List<Object> ob = listob.get(i);
Advertising advertising = new Advertising();
//设置编号
//通过遍历实现把每一列封装成一个model中,再把所有的model用List集合装载
advertising.setTitle(String.valueOf(ob.get(1)));
advertising.setIntro(String.valueOf(ob.get(2)));
// advertising.setUrl(String.valueOf(ob.get(3)));
advertising.setUrl(String.valueOf(ob.get(3)));
//object类型转Double类型
advertisingList.add(advertising);
}
//批量插入
advertisingMapper.insertInfoBatch(advertisingList);
}
接着是mapper.xml,用<foreach></foreach>实现数据的批量插入
<insert id="insertInfoBatch" parameterType="java.util.List">
insert into up_advertising (title, intro)
values
<foreach collection="advertisingList" item="item" index="index" separator=",">
(#{item.title}, #{item.intro})
</foreach>
</insert>
还有一个实体类
package com.heitian.ssm.model;
public class Advertising {
private Integer id;
private String title;
private String intro;
private String img;
private String url;
private Integer number;
private Integer type;
private Integer oneid;
private Integer twoid;
private Integer thereid;
private Integer contentid;
private Integer port;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title == null ? null : title.trim();
}
public String getIntro() {
return intro;
}
public void setIntro(String intro) {
this.intro = intro == null ? null : intro.trim();
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img == null ? null : img.trim();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Integer getOneid() {
return oneid;
}
public void setOneid(Integer oneid) {
this.oneid = oneid;
}
public Integer getTwoid() {
return twoid;
}
public void setTwoid(Integer twoid) {
this.twoid = twoid;
}
public Integer getThereid() {
return thereid;
}
public void setThereid(Integer thereid) {
this.thereid = thereid;
}
public Integer getContentid() {
return contentid;
}
public void setContentid(Integer contentid) {
this.contentid = contentid;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
}
到这里,excel表的导入功能便完成了。这里补充一下mybatis里<foreach>里面的部分参数,collection是传入参数的类型,如果传入参数是List,这里便是list,如果是一个数组,便是array,separator指的是数据之间用“,”隔开,这也是借鉴了mysql插入多条数据的写法,具体的执行效率还没做多的探讨,我试过导入30条数据,效率还是可以接受的,如果有人有更好的写法,欢迎留言交流。
Excel导出Controller端实现
/**
* 测试 excel 导出
*/
@RequestMapping("/excelAvdImpot.do")
@ResponseBody
public void excelAvdImpot(HttpServletRequest request, HttpServletResponse response) throws ClassNotFoundException, IntrospectionException, IllegalAccessException, ParseException, InvocationTargetException {
String salaryDate = request.getParameter("salaryDate");
if(salaryDate!=""){
response.reset(); //清除buffer缓存
Map<String,Object> map=new HashMap<String,Object>();
// 指定下载的文件名
response.setHeader("Content-Disposition", "attachment;filename="+salaryDate+".xlsx");
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
XSSFWorkbook workbook=null;
//导出Excel对象
workbook = advertisingService.exportExcelInfo(salaryDate);
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
bufferedOutPut.flush();
workbook.write(bufferedOutPut);
bufferedOutPut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Service层,这里也是只写接口exportExcelInfo的实现方法
/**
* 导出
* @param salaryDate
* @return
* @throws InvocationTargetException
* @throws ClassNotFoundException
* @throws IntrospectionException
* @throws ParseException
* @throws IllegalAccessException
*/
public XSSFWorkbook exportExcelInfo(String salaryDate) throws InvocationTargetException, ClassNotFoundException, IntrospectionException, ParseException, IllegalAccessException{
//根据条件查询数据,把数据装载到一个list中
List<Advertising> list = advertisingMapper.selectApartInfo(salaryDate);
List<ExcelBean> excel=new ArrayList<ExcelBean>();
Map<Integer,List<ExcelBean>> map=new LinkedHashMap<Integer,List<ExcelBean>>();
XSSFWorkbook xssfWorkbook=null;
//设置标题栏
excel.add(new ExcelBean("序号","id",0));
excel.add(new ExcelBean("标题","title",0));
excel.add(new ExcelBean("简介","intro",0));
excel.add(new ExcelBean("链接地址","url",0));
map.put(0, excel);
String sheetName = salaryDate + "月份收入";
//调用ExcelUtil的方法
xssfWorkbook = ExcelUtil.createExcelFile(Advertising.class, list, map, sheetName);
return xssfWorkbook;
}
导出的 XML
<select id="selectApartInfo" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from up_advertising
</select>
- 这里不写出导出功能的mapper.xml实现语句了,具体实现也就是数据查询,把查询出来的数据转载到一个List中。
- 以上便是在SSM下使用POI实现excel表的导入和导出的整体思路,主要的导入和导出的核心方法都封装在Excel的工具类中,但面对具体的表格需要具体分析循环的开始,以便能够去除表头或者标题栏。