码迷,mamicode.com
首页 > 其他好文 > 详细

Excel 工具类

时间:2020-10-29 10:35:46      阅读:21      评论:0      收藏:0      [点我收藏+]

标签:add   ogg   文件   mes   actor   org   rownum   mode   creates   

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import cn.com.amway.msgcenter.console.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**

  • excel工具类
  • @helen
  • */
    public class ExcelUtils {
    private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);

    /**

    • Read the Excel 2020
    • @param path the path of the excel file
    • @return
    • @throws IOException
      */
      private static List<List<String>> readXlsx(InputStream is) throws IOException {
      XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
      // Read the Sheet
      XSSFSheet xssfSheet=null;
      XSSFRow xssfRow=null;
      List<List<String>> list=new ArrayList<List<String>>();
      for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
      xssfSheet = xssfWorkbook.getSheetAt(numSheet);

      if (xssfSheet == null) {
          continue;
      }
      
      // Read the Row
      for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
          xssfRow = xssfSheet.getRow(rowNum);
          if (xssfRow != null) {
              list.add(parseRow(xssfRow));
          }
      }

      }
      return list;
      }

    /**

    • Read the Excel 2003-2007
    • @param path the path of the Excel
    • @return
    • @throws IOException
      */
      private static List<List<String>> readXls(InputStream is) throws IOException {
      HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
      // Read the Sheet
      HSSFSheet hssfSheet=null;
      HSSFRow hssfRow=null;
      List<List<String>> list=new ArrayList<List<String>>();;
      for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
      hssfSheet = hssfWorkbook.getSheetAt(numSheet);
      if (hssfSheet == null) {
      continue;
      }

      // Read the Row
      for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
          hssfRow = hssfSheet.getRow(rowNum);
          if(null!=hssfRow){
              list.add(parseRow(hssfRow));
          }
      }

      }
      return list;
      }

    private static List<String> parseRow(HSSFRow hssfRow){
    Iterator<Cell> iterator=hssfRow.cellIterator();
    List<String> list=new ArrayList<String>();
    while(iterator.hasNext()){
    list.add(getValue((HSSFCell)iterator.next()));
    }
    return list;
    }

    private static List<String> parseRow(XSSFRow xssfRow){
    Iterator<Cell> iterator=xssfRow.cellIterator();
    List<String> list=new ArrayList<String>();
    while(iterator.hasNext()){
    list.add(getValue((XSSFCell)iterator.next()));
    }
    return list;
    }

    @SuppressWarnings("static-access")
    private static String getValue(XSSFCell xssfRow) {
    if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
    return String.valueOf(xssfRow.getBooleanCellValue());
    } else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
    return String.valueOf(xssfRow.getNumericCellValue());
    } else {
    if(StringUtils.isEmpty(xssfRow.getStringCellValue())){
    return null;
    }else{
    return String.valueOf(xssfRow.getStringCellValue());
    }

    }

    }

    @SuppressWarnings("static-access")
    private static String getValue(HSSFCell hssfCell) {
    if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
    return String.valueOf(hssfCell.getBooleanCellValue());
    } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
    return String.valueOf(hssfCell.getNumericCellValue());
    } else {
    if(StringUtils.isEmpty(hssfCell.getStringCellValue())){
    return null;
    }else{
    return String.valueOf(hssfCell.getStringCellValue());
    }
    }
    }

    /**

    • 导出xlsx文件
    • @param fileName 文件名
    • @param sheetName 表格名
    • @param list 数据
      */
      public static void writeXlsxByCache(String fileName, String sheetName, List<String> headList, List<List<String>> list) throws Exception{
      Workbook wb = new SXSSFWorkbook(500);
      try {
      Sheet sheet = wb.createSheet(sheetName);
      List<String> strList = null;
      Row row = null;
      Cell cell = null;
      addHead(sheet, headList);
      for (int i = 0; i < list.size(); i++) {
      row = sheet.createRow(i + 1);
      strList = list.get(i);
      for (int j = 0; j < strList.size(); j++) {
      cell = row.createCell(j);
      cell.setCellValue(strList.get(j));
      }
      }
      FileOutputStream outputStream = new FileOutputStream(fileName);
      wb.write(outputStream);
      outputStream.close();
      } catch (FileNotFoundException e) {
      logger.error("创建文件出现异常:" + e.getMessage(), e);
      throw e;
      } catch (IOException e) {
      logger.error("打开文件流出现异常:" + e.getMessage(), e);
      throw e;
      } finally {
      if (null != wb) {
      try {
      wb.close();
      } catch (IOException e) {
      logger.error("关闭文件出现异常:" + e.getMessage(), e);
      }
      }
      }
      }

    /**

    • 导出xlsx文件
    • @param fileName 文件名
    • @param sheetName 表格名
    • @param list 数据
      */
      public static void writeXlsxByCache(String fileName, String sheetName, List<String> head, List<?> list,Class clazz) throws Exception{
      XSSFWorkbook wb = new XSSFWorkbook();
      SXSSFWorkbook swb = new SXSSFWorkbook(wb,500,true,true);
      try {
      Sheet sheet = swb.createSheet(sheetName);
      String fieldName;
      Method method;
      String methodEnd;
      Row row = null;
      Cell cell = null;
      addHead(sheet, head);
      Object object;
      String str=null;
      for(int i = 0; i < list.size(); i++){
      row = sheet.createRow(i + 1);

          for (int j = 0; j < head.size(); j++) {
              fieldName=head.get(j);
              methodEnd=fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
              method=clazz.getMethod("get"+methodEnd);
              object=method.invoke(list.get(i));
              if(null==object){
                  str="";
              }else{
                  str=String.valueOf(object);
              }
              cell = row.createCell(j);
              cell.setCellValue(str);
          }
      }
       FileOutputStream outputStream = new FileOutputStream(fileName);
       swb.write(outputStream);
       outputStream.close();
       swb.close();
       wb.close();

      } catch (Exception e) {
      logger.error("打开文件流出现异常:" + e.getMessage(), e);
      throw e;
      } finally {
      }
      }

    public static void addHead(Sheet sheet, List<String> headList) {
    Row row = null;
    Cell cell = null;
    row = sheet.createRow(0);
    for (int i = 0; i < headList.size(); i++) {
    cell = row.createCell(i);
    cell.setCellValue(headList.get(i));
    }

    }

}

Excel 工具类

标签:add   ogg   文件   mes   actor   org   rownum   mode   creates   

原文地址:https://blog.51cto.com/7218743/2544684

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!