環境:導入POI對應的包
環境:
Spring+SpringMVC+Mybatis
POI對應的包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
ExcelBean數據封裝
ExcelBean.java:
/**
* Created by LT on 2017-08-23.
*/
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;
}
}
導入導出工具類
ExcelUtil.java
/**
* Created by LT on 2017-08-23.
*/
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) 11);// 設置字體大小
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) 12);// 設置字體大小
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_RIGHT); // 居中
}
/**
* 根據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) {
value = DateUtils.dateToString((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表導出
ExcelController.java
/**
* 上傳excel並將內容導入數據庫中
*
* @return
*/
@RequestMapping(value = "/import")
@Permission("login")
public Object importExcel(MultipartFile file, HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
try {
if (request.getSession().getAttribute("userName") == null || request.getSession().getAttribute("userName").toString().isEmpty()) {
map.put("code", "20000");
map.put("mes", "請先登錄再進行操作!!!");
return map;
}
System.out.println(file.getOriginalFilename());
InputStream in = file.getInputStream();
List<List<Object>> listob = ExcelUtil.getBankListByExcel(in, file.getOriginalFilename());
List<Inventory> inventoryList = new ArrayList<Inventory>();
String createBy = request.getSession().getAttribute("userName").toString();
//遍歷listob數據,把數據放到List中
for (int i = 0; i < listob.size(); i++) {
List<Object> ob = listob.get(i);
Inventory inventory = new Inventory();
//通過遍歷實現把每一列封裝成一個model中,再把所有的model用List集合裝載
inventory.setCompany(String.valueOf(ob.get(0)).trim());
inventory.setArea(String.valueOf(ob.get(1)).trim());
inventory.setWarehouse(String.valueOf(ob.get(2)).trim());
inventory.setWarehouseName(String.valueOf(ob.get(3)).trim());
inventory.setStoreAttributes(String.valueOf(ob.get(4)).trim());
inventory.setMaterialBig(String.valueOf(ob.get(5)).trim());
inventory.setMaterialMid(String.valueOf(ob.get(6)).trim());
inventory.setMaterialSmall(String.valueOf(ob.get(7)).trim());
inventory.setMaterialModel(String.valueOf(ob.get(8)).trim());
inventory.setMaterialCode(String.valueOf(ob.get(9)).trim());
inventory.setMaterialTips(String.valueOf(ob.get(10)).trim());
inventory.setServiceAttribute(String.valueOf(ob.get(11)).trim());
inventory.setPlanner(String.valueOf(ob.get(12)).trim());
inventory.setSales(String.valueOf(ob.get(13)).trim());
inventory.setEndingCount(String.valueOf(ob.get(14)).trim());
inventory.setTransferin(String.valueOf(ob.get(15)).trim());
inventory.setInventory(String.valueOf(ob.get(16)).trim());
inventory.setCreateTime(new Date());
inventory.setCreateBy(createBy);
inventoryList.add(inventory);
}
//批量插入
inventoryService.insertInfoBatch(inventoryList);
} catch (Exception e) {
LogUtil.error("ExcelController-----importExcel:" + e.getMessage());
map.put("code", "30000");
map.put("mes", "上傳異常");
return map;
}
map.put("code", "10000");
map.put("mes", "上傳成功");
map.put("url","user/crud");
LogUtil.info("ExcelController-----importExcel:" + map.toString());
return map;
}
Excel表導出
ExcelController.java
/**
* 將數據庫中的數據導出為excel
*
* @return
*/
@RequestMapping("/output")
@Permission("login")
@ResponseBody
public Object outputExcel(HttpServletRequest request, HttpServletResponse response) {
response.reset(); //清除buffer緩存
Map<String, Object> map = new HashMap<String, Object>(), TempMap = new HashMap<String, Object>();
System.out.println("startDate:"+request.getParameter("startDate"));
System.out.println("endDate:"+request.getParameter("endDate"));
try {
if (request.getSession().getAttribute("userName") == null || request.getSession().getAttribute("userName").toString().isEmpty()) {
map.put("code", "20000");
map.put("mes", "請先登錄再進行操作!!!");
return map;
}
String fileName = DateUtils.getCurrentDate() + "~";
if (request.getParameter("startDate") != null&& !"".equals(request.getParameter("startDate"))) {
TempMap.put("startDate", request.getParameter("startDate"));
fileName = DateUtils.formatString(request.getParameter("startDate"))+ "~";
}
if (request.getParameter("endDate") != null&&!"".equals(request.getParameter("endDate"))) {
TempMap.put("endDate", request.getParameter("endDate"));
fileName =fileName+ DateUtils.formatString(request.getParameter("endDate"));
} else {
fileName = fileName + DateUtils.dateToString(new Date());
}
// 指定下載的文件名
response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".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);
List<Inventory> list = inventoryService.getList(TempMap);
List<ExcelBean> excel = new ArrayList<ExcelBean>();
Map<Integer, List<ExcelBean>> mapExcel = new LinkedHashMap<Integer, List<ExcelBean>>();
XSSFWorkbook xssfWorkbook = null;
//設置標題欄
excel.add(new ExcelBean("行政公司", "company", 0));
excel.add(new ExcelBean("區域", "area", 0));
excel.add(new ExcelBean("門店-倉庫", "warehouse", 0));
excel.add(new ExcelBean("門店-倉庫名稱", "warehouseName", 0));
excel.add(new ExcelBean("門店屬性", "storeAttributes", 0));
excel.add(new ExcelBean("物料大類", "materialBig", 0));
excel.add(new ExcelBean("物料中類(手機制式)", "materialMid", 0));
excel.add(new ExcelBean("物料小類", "materialSmall", 0));
excel.add(new ExcelBean("物料型號", "materialModel", 0));
excel.add(new ExcelBean("物料編碼", "materialCode", 0));
excel.add(new ExcelBean("物料說明", "materialTips", 0));
excel.add(new ExcelBean("業務屬性", "serviceAttribute", 0));
excel.add(new ExcelBean("計划員", "planner", 0));
excel.add(new ExcelBean("銷量", "sales", 0));
excel.add(new ExcelBean("期末數量", "endingCount", 0));
excel.add(new ExcelBean("調撥在途", "transferin", 0));
excel.add(new ExcelBean("庫存", "inventory", 0));
mapExcel.put(0, excel);
String sheetName = fileName + "天翼庫存表";
xssfWorkbook = ExcelUtil.createExcelFile(Inventory.class, list, mapExcel, sheetName);
OutputStream output;
try {
output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
bufferedOutPut.flush();
xssfWorkbook.write(bufferedOutPut);
bufferedOutPut.close();
} catch (IOException e) {
LogUtil.error("ExcelController-----outputExcel:" + e.getMessage());
e.printStackTrace();
map.put("code", "30000");
map.put("mes", "導出異常");
return map;
}
} catch (Exception e) {
LogUtil.error("ExcelController-----outputExcel:" + e.getMessage());
map.put("code", "30000");
map.put("mes", "導出異常");
return map;
}
map.put("code", "10000");
map.put("mes", "導出成功");
LogUtil.info("ExcelController-----outputExcel:" + map.toString());
return map;
}
mapper.xml配置
InventoryMapping.xml
<insert id="insertInfoBatch" parameterType="java.util.List">
insert into inventory (
company, area,warehouse, warehouseName, storeAttributes,materialBig,
materialMid, materialSmall, materialModel, materialCode, materialTips,serviceAttribute,
planner , sales, endingCount, transferin, inventory, createTime, createBy
)
values
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.company}, #{item.area}, #{item.warehouse},#{item.warehouseName}, #{item.storeAttributes}, #{item.materialBig},
#{item.materialMid},#{item.materialSmall}, #{item.materialModel},#{item.materialCode}, #{item.materialTips}, #{item.serviceAttribute},
#{item.planner}, #{item.sales}, #{item.endingCount},#{item.transferin}, #{item.inventory}, #{item.createTime}, #{item.createBy}
)
</foreach>
</insert>
參考網址:https://cloud.tencent.com/developer/article/1436939
