如何在SSM中實現Excel的導入到處呢,用POI就可以解決了!!下邊我直接上代碼!
pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
ExcelBean
package com.xxx.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;
}
}
ExcelUtil,最重要的工具類
package com.xxx.util;
import com.shitong.pojo.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.*;
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.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
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<>();
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) {
DateFormat format = new SimpleDateFormat("yyyy-MM-DD");
value = format.format(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);
}
}
}
上面的都是通用的代碼,下邊分別是導入導出的代碼:
1.導入
jsp頁面:
<form id="form" method="post" action="/azcitem/import" enctype="multipart/form-data">
<div style="margin: 10px;" class="btn btn-primary">
<input id="file" type="file" name="file"/>
<input id="excel_button" type="submit" value="導入" />
<div >
</div>
</div>
</form>
Controller:
@RequestMapping("/import")
@ResponseBody
public Object impotr(@RequestParam("file")CommonsMultipartFile file){
Result result = new Result();
try {
InputStream in = file.getInputStream();
azcItemInfoService.importExcelInfo(in,file);
in.close();
result.setMsg("ok");
result.setStatue(200);
}catch (Exception e){
result.setMsg("err");
result.setStatue(500);
}
return JSONObject.toJSON(result);
}
Service:
@Override
public void importExcelInfo(InputStream in, MultipartFile file) {
try{
List<List<Object>> listob = ExcelUtil.getBankListByExcel(in,file.getOriginalFilename());
List<AzcItemInfo> azcitemList = new ArrayList<AzcItemInfo>();
//遍歷listob數據,把數據放到List中
for (int i = 0; i < listob.size(); i++) {
List<Object> ob = listob.get(i);
AzcItemInfo azcItemInfo =new AzcItemInfo();
azcItemInfo.setId(String.valueOf(ob.get(0)));
azcItemInfo.setName(String.valueOf(ob.get(1)));
azcItemInfo.setItemurl(String.valueOf(ob.get(2)));
azcItemInfo.setClassfy(String.valueOf(ob.get(3)));
azcItemInfo.setZrf(String.valueOf(ob.get(4)));
azcItemInfo.setDate(String.valueOf(ob.get(5)));
azcitemList.add(azcItemInfo);
}
azcItemInfoMapper.insertAzcItemList(azcitemList);
}catch (Exception e){
e.printStackTrace();
}
}
2.導出
Controller:@RequestMapping("/export")
public void export(HttpServletResponse response,String idList) {
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=AzcItemInfo.xlsx;charset=UTF-8");
XSSFWorkbook workbook = azcItemInfoService.exportExcelInfo(idList);
try {
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
workbook.write(bufferedOutPut);
bufferedOutPut.flush();
bufferedOutPut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Service:
@Override
public XSSFWorkbook exportExcelInfo(String idList) {
XSSFWorkbook xssfWorkbook=null;
try {
//根據ID查找數據
String[] list = idList.split(",");
List<AzcItemInfo> azcItemInfoList = new ArrayList<AzcItemInfo>();
for(int i=0;i<list.length;i++){
AzcItemInfo azcItemInfo = azcItemInfoMapper.selectByPrimaryKey(list[i]);
azcItemInfoList.add(azcItemInfo);
}
List<ExcelBean> excel=new ArrayList<>();
Map<Integer,List<ExcelBean>> map=new LinkedHashMap<>();
//設置標題欄
excel.add(new ExcelBean("ID","id",0));
excel.add(new ExcelBean("名稱","name",0));
excel.add(new ExcelBean("itemurl","itemurl",0));
excel.add(new ExcelBean("classfy","classfy",0));
excel.add(new ExcelBean("zrf","zrf",0));
excel.add(new ExcelBean("date","date",0));
map.put(0, excel);
String sheetName ="AzcItemInfo";
xssfWorkbook = ExcelUtil.createExcelFile(AzcItemInfo.class, azcItemInfoList, map, sheetName);
} catch (Exception e) {
e.printStackTrace();
}
return xssfWorkbook;
}
以上就是導入導出的代碼了,主要是工具類的寫法了!重要的是你導出的時候千萬千萬不能用ajax提交請求,要不然下載的頁面是不會彈出來的,你可以用下面的代碼達到發送請求的目的:
windows.location.href='xxxxxx/export'