导入导出Utils-项目分析

导出文件
/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao ([email protected]) ***/
package com.tkn.zh.common.utils.excel;

import com.google.common.collect.Lists;
import com.tkn.zh.common.utils.Encodes;
import com.tkn.zh.common.utils.FileEncodeUtil;
import com.tkn.zh.core.dict.util.DictUtil;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExportExcel {
   private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
   private SXSSFWorkbook wb;
   private Sheet sheet;
   private Map<String, CellStyle> styles;
   private int rownum;

   public ExportExcel(String title, String[] headers) {
      initialize(title, Lists.newArrayList(headers));
   }

   public ExportExcel(String title, List<String> headerList) {
      initialize(title, headerList);
   }

   private void initialize(String title, List<String> headerList) {
      this.wb = new SXSSFWorkbook(500);
      this.sheet = this.wb.createSheet((StringUtils
            .isNoneBlank(new CharSequence[] { title })) ? title : "Export");
      this.styles = createStyles(this.wb);

      if (StringUtils.isNotBlank(title)) {
         Row titleRow = this.sheet.createRow(this.rownum++);
         titleRow.setHeightInPoints(30.0F);
         Cell titleCell = titleRow.createCell(0);
         titleCell.setCellStyle((CellStyle) this.styles.get("title"));
         titleCell.setCellValue(title);
         this.sheet.addMergedRegion(new CellRangeAddress(titleRow
               .getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(),
               headerList.size() - 1));
      }

      if (headerList == null) {
         throw new RuntimeException("headerList not null!");
      }
      Row headerRow = this.sheet.createRow(this.rownum++);
      headerRow.setHeightInPoints(16.0F);
      for (int i = 0; i < headerList.size(); ++i) {
         Cell cell = headerRow.createCell(i);
         cell.setCellStyle((CellStyle) this.styles.get("header"));
         String[] ss = StringUtils
               .split((String) headerList.get(i), "**", 2);
         if (ss.length == 2) {
            cell.setCellValue(ss[0]);
            Comment comment = this.sheet.createDrawingPatriarch()
                  .createCellComment(
                        new XSSFClientAnchor(0, 0, 0, 0, 3, 3, 5, 6));
            comment.setString(new XSSFRichTextString(ss[1]));
            cell.setCellComment(comment);
         } else {
            cell.setCellValue((String) headerList.get(i));
         }
         this.sheet.autoSizeColumn(i);
      }
      for (int i = 0; i < headerList.size(); ++i) {
         int colWidth = this.sheet.getColumnWidth(i) * 2;
         this.sheet.setColumnWidth(i, (colWidth < 3000) ? 3000 : colWidth);
      }
      log.debug("Initialize success.");
   }

   /**
    * 创建表格样式
    * 
    * @param wb
    *            工作薄对象
    * @return 样式列表
    */
   private Map<String, CellStyle> createStyles(Workbook wb) {
      Map<String, CellStyle> styles = new HashMap<String, CellStyle>();

      CellStyle style = wb.createCellStyle();
      style.setAlignment(CellStyle.ALIGN_CENTER);
      style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
      Font titleFont = wb.createFont();
      titleFont.setFontName("Arial");
      titleFont.setFontHeightInPoints((short) 16);
      titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
      style.setFont(titleFont);
      styles.put("title", style);

      style = wb.createCellStyle();
      style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
      style.setBorderRight(CellStyle.BORDER_THIN);
      style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
      style.setBorderLeft(CellStyle.BORDER_THIN);
      style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
      style.setBorderTop(CellStyle.BORDER_THIN);
      style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
      style.setBorderBottom(CellStyle.BORDER_THIN);
      style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
      Font dataFont = wb.createFont();
      dataFont.setFontName("Arial");
      dataFont.setFontHeightInPoints((short) 10);
      style.setFont(dataFont);
      styles.put("data", style);

      style = wb.createCellStyle();
      style.cloneStyleFrom(styles.get("data"));
      style.setAlignment(CellStyle.ALIGN_LEFT);
      styles.put("data1", style);

      style = wb.createCellStyle();
      style.cloneStyleFrom(styles.get("data"));
      style.setAlignment(CellStyle.ALIGN_CENTER);
      styles.put("data2", style);

      style = wb.createCellStyle();
      style.cloneStyleFrom(styles.get("data"));
      style.setAlignment(CellStyle.ALIGN_RIGHT);
      styles.put("data3", style);

      style = wb.createCellStyle();
      style.cloneStyleFrom(styles.get("data"));
      // style.setWrapText(true);
      style.setAlignment(CellStyle.ALIGN_CENTER);
      style.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
      style.setFillPattern(CellStyle.SOLID_FOREGROUND);
      Font headerFont = wb.createFont();
      headerFont.setFontName("Arial"); 
      headerFont.setFontHeightInPoints((short) 10);
      headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
      headerFont.setColor(IndexedColors.WHITE.getIndex());
      style.setFont(headerFont);
      styles.put("header", style);

      return styles;
   }

   public Row addRow() {
      return this.sheet.createRow(this.rownum++);
   }

   public Cell addCell(Row row, int column, Object val) {
      return addCell(row, column, val, 0, Class.class);
   }

   /**
    * 添加一个单元格
    * 
    * @param row
    *            添加的行
    * @param column
    *            添加列号
    * @param val
    *            添加值
    * @param align
    *            对齐方式(1:靠左;2:居中;3:靠右)
    * @return 单元格对象
    */
   public Cell addCell(Row row, int column, Object val, int align,
         Class<?> fieldType) {
      Cell cell = row.createCell(column);
      CellStyle style = styles.get("data"
            + (align >= 1 && align <= 3 ? align : ""));
      try {
         if (val == null) {
            cell.setCellValue("");
         } else if (val instanceof String) {
            cell.setCellValue((String) val);
         } else if (val instanceof Integer) {
            cell.setCellValue((Integer) val);
         } else if (val instanceof Long) {
            cell.setCellValue((Long) val);
         } else if (val instanceof Double) {
            cell.setCellValue((Double) val);
         } else if (val instanceof Float) {
            cell.setCellValue((Float) val);
         } else if (val instanceof Date) {
            DataFormat format = wb.createDataFormat();
            style.setDataFormat(format.getFormat("yyyy-MM-dd"));
            cell.setCellValue((Date) val);
         } else {
            if (fieldType != Class.class) {
               cell.setCellValue((String) fieldType.getMethod("setValue",
                     Object.class).invoke(null, val));
            } else {
               cell.setCellValue((String) Class
                     .forName(
                           this.getClass()
                                 .getName()
                                 .replaceAll(
                                       this.getClass()
                                             .getSimpleName(),
                                       "fieldtype."
                                             + val.getClass()
                                                   .getSimpleName()
                                             + "Type"))
                     .getMethod("setValue", Object.class)
                     .invoke(null, val));
            }
         }
      } catch (Exception ex) {
         log.info("Set cell value [" + row.getRowNum() + "," + column
               + "] error: " + ex.toString());
         cell.setCellValue(val.toString());
      }
      cell.setCellStyle(style);
      return cell;
   }

   public ExportExcel write(OutputStream os) throws IOException {
      this.wb.write(os);
      return this;
   }

   public ExportExcel write(HttpServletResponse response, String fileName)
         throws IOException {
      response.reset();
      response.setContentType("application/octet-stream; charset=utf-8");
      response.setHeader("Content-Disposition", "attachment; filename="
            + Encodes.urlEncode(fileName));
      write(response.getOutputStream());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      return this;
   }

   public ExportExcel write(HttpServletRequest request,
         HttpServletResponse response, String fileName) throws IOException {
      response.reset();
      response.setContentType("application/octet-stream; charset=utf-8");
      response.setHeader("Content-Disposition", "attachment; filename="
            + FileEncodeUtil.encodeFilename(fileName, request));
      write(response.getOutputStream());
      response.getOutputStream().flush();
      response.getOutputStream().close();
      return this;
   }

   public ExportExcel writeFile(String name) throws FileNotFoundException,
         IOException {
      FileOutputStream os = new FileOutputStream(name);
      write(os);
      return this;
   }

   public <E> ExportExcel setDataList(List<E> list) {
      for (Object e : list) {
         int colunm = 0;
         Row row = addRow();
         StringBuilder sb = new StringBuilder();
         Map<String, Object> map = (Map) e;
         for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object val = null;
            try {
               val = entry.getValue();
               String dictType = (String) map.get("dict_type");
               if (StringUtils.isNotBlank(dictType))
                  val = DictUtil.getDictLabel(
                        (val == null) ? "" : val.toString(), dictType,
                        "");
            } catch (Exception ex) {
               log.info(ex.toString());
               val = "";
            }
            addCell(row, colunm++, val);
            sb.append(val + ", ");
         }
         log.debug("Write success: [" + row.getRowNum() + "] "
               + sb.toString());
      }
      return this;
   }

   public <E> ExportExcel setDataList(List<E> list,
         Map<String, Object> tableInfo) {
      for (Object e : list) {
         int colunm = 0;
         Row row = addRow();
         StringBuilder sb = new StringBuilder();
         Map<String, Object> map = (Map) e;
         for (Map.Entry<String, Object> entry : map.entrySet()) {
            Object val = null;
            try {
               val = entry.getValue();
               if ((tableInfo != null) && (!(tableInfo.isEmpty()))) {
                  String dictType = (String) tableInfo
                        .get(entry.getKey());
                  if (StringUtils.isNotBlank(dictType)) {
                     val = DictUtil.getDictLabel((val == null) ? ""
                           : val.toString(), dictType, "");
                  }
               }
            } catch (Exception ex) {
               log.info(ex.toString());
               val = "";
            }
            addCell(row, colunm++, val);
            sb.append(val + ", ");
         }
         log.debug("Write success: [" + row.getRowNum() + "] "
               + sb.toString());
      }
      return this;
   }
   
   public <E> ExportExcel setFilterDataList(List<Map<String, Object>> list, List<String> keyList) {
      for (Map<String, Object> map : list) {
         int colunm = 0;
         Row row = addRow();
         for (String key : keyList) {
            String value = String.valueOf(map.get(key));
            if (StringUtils.isEmpty(value) || "null".equals(value)) {
               value = "";
            }
            addCell(row, colunm++, value);
         }
      }
      return this;
   }

   public ExportExcel dispose() {
      this.wb.dispose();
      return this;
   }
}

/**导入文件**/

/*** Eclipse Class Decompiler plugin, copyright (c) 2016 Chen Chao ([email protected]) ***/
package com.tkn.zh.common.utils.excel;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ImportExcel {
   private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
   private Workbook wb;
   private Sheet sheet;
   private int headerNum;

   public ImportExcel(String fileName, int headerNum)
         throws InvalidFormatException, IOException {
      this(new File(fileName), headerNum);
   }

   public ImportExcel(File file, int headerNum) throws InvalidFormatException,
         IOException {
      this(file, headerNum, 0);
   }

   public ImportExcel(String fileName, int headerNum, int sheetIndex)
         throws InvalidFormatException, IOException {
      this(new File(fileName), headerNum, sheetIndex);
   }

   public ImportExcel(File file, int headerNum, int sheetIndex)
         throws InvalidFormatException, IOException {
      this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
   }

   public ImportExcel(MultipartFile multipartFile, int headerNum,
         int sheetIndex) throws InvalidFormatException, IOException {
      this(multipartFile.getOriginalFilename(), multipartFile
            .getInputStream(), headerNum, sheetIndex);
   }

   public ImportExcel(String fileName, InputStream is, int headerNum,
         int sheetIndex) throws InvalidFormatException, IOException {
      if (StringUtils.isBlank(fileName))
            throw new RuntimeException("导入文档为空!");
          if (fileName.toLowerCase().endsWith("xls"))
            this.wb = new HSSFWorkbook(is);
          else if (fileName.toLowerCase().endsWith("xlsx"))
            this.wb = new XSSFWorkbook(is);
          else {
            throw new RuntimeException("文档格式不正确!");
          }
          if (this.wb.getNumberOfSheets() < sheetIndex) {
            throw new RuntimeException("文档中没有工作表!");
          }
      this.sheet = this.wb.getSheetAt(sheetIndex);
      this.headerNum = headerNum;
      log.debug("Initialize success.");
   }

   public Row getRow(int rownum) {
      return this.sheet.getRow(rownum);
   }

   public int getDataRowNum() {
      return (this.headerNum + 1);
   }

   public int getLastDataRowNum() {
      return (this.sheet.getLastRowNum() + this.headerNum);
   }

   public int getLastCellNum() {
      return getRow(this.headerNum).getLastCellNum();
   }

   public List<Object> getHeader() {
      List list = Lists.newArrayList();
      Row row = getRow(this.headerNum);
      for (int i = 0; i < getLastCellNum(); ++i) {
         list.add(getCellValue(row, i));
      }
      return list;
   }

   public List<Map<Object, Object>> getDataList() {
      List header = getHeader();
      List list = Lists.newLinkedList();
      for (int i = getDataRowNum(); i < getLastDataRowNum() + 1; ++i) {
         Row row = getRow(i);
         Map map = Maps.newHashMap();
         for (int j = 0; j < getLastCellNum(); ++j) {
            Object obj = getCellValue(row, j);
            map.put(header.get(j), obj);
         }
         list.add(map);
      }
      return list;
   }
   
   public Map<String, Object> getAttendDataList() {
      try {
         List header = getHeader();
         Row monthRow = getRow(2);
         String month = String.valueOf(getCellValue(monthRow, 2)).substring(0, 8);
         Map<String, Object> resultMap = new HashMap<String, Object>();
         String userNo = "";
         for (int i = getDataRowNum(); i < getLastDataRowNum() + 1; ++i) {
            Row row = getRow(i);
            if (i % 2 == 0) {
               userNo = String.valueOf(getCellValue(row, 2));
            } else {
               Map<String, Object> map = Maps.newHashMap();
               for (int j = 0; j < getLastCellNum(); ++j) {
                  Object obj = getCellValue(row, j);
                  String key = "";
                  String headerKey = String.valueOf(header.get(j));
                  if (StringUtils.isEmpty(headerKey)) {
                     continue;
                  }
                  Integer day = (int)Double.parseDouble(headerKey);
                  if (day < 10) {
                     key = month + "0" + day.toString();
                  } else {
                     key = month + day.toString();
                  }
                  map.put(key, obj);
               }
               resultMap.put(userNo, map);
            }
         }
         return resultMap;
      } catch (Exception e) {
         return null;
      }
   }

   public Object getCellValue(Row row, int column) {
      Object val = "";
      try {
         Cell cell = row.getCell(column);
         if (cell != null)
            if (cell.getCellType() == 0)
               val = Double.valueOf(cell.getNumericCellValue());
            else if (cell.getCellType() == 1)
               val = cell.getStringCellValue();
            else if (cell.getCellType() == 2)
               val = cell.getCellFormula();
            else if (cell.getCellType() == 4)
               val = Boolean.valueOf(cell.getBooleanCellValue());
            else if (cell.getCellType() == 5)
               val = Byte.valueOf(cell.getErrorCellValue());
      } catch (Exception e) {
         return val;
      }
      return val;
   }
}




猜你喜欢

转载自blog.csdn.net/Lujunwei0205/article/details/80239453
今日推荐