Java read write Excel instance sharing

  • 2020-05-27 05:25:40
  • OfStack

Without further ado, look at the code:

ExcelUtil.java


package pers.kangxu.datautils.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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;
/**
 * 
 * <b>
 *  excel  tool 
 * </b>
 * @author kangxu
 *
 */
public class ExcelUtil {
  /**
   *  export  excel
   * @param filePath  File full path 
   * @param sheetName sheet The name of the page 
   * @param sheetIndex  The current sheet The following table   from 0 start 
   * @param fileHeader  The head 
   * @param datas  content 
   */
  public static void writeExcel(String filePath,String sheetName,
                  int sheetIndex,
                  String[] fileHeader,
                  List<String[]> datas){
    //  Create a workbook 
    Workbook wb = new HSSFWorkbook();
    //  Create worksheets  sheet
    Sheet s = wb.createSheet();
    wb.setSheetName(sheetIndex, sheetName);
    Row r = s.createRow(0);
    Cell c = null;
    Font font = null; 
    CellStyle styleHeader = null; 
    CellStyle styleContent = null;
    // The bold  
    font = wb.createFont(); 
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
    //  Set header style 
    styleHeader = wb.createCellStyle(); 
    styleHeader.setFont(font); 
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN); // Under the frame   
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);// The left margin   
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);// On the border   
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);// Right margin  
    //  Set content style 
    styleContent = wb.createCellStyle();
    styleContent.setBorderBottom(HSSFCellStyle.BORDER_THIN); // Under the frame   
    styleContent.setBorderLeft(HSSFCellStyle.BORDER_THIN);// The left margin   
    styleContent.setBorderTop(HSSFCellStyle.BORDER_THIN);// On the border   
    styleContent.setBorderRight(HSSFCellStyle.BORDER_THIN);// Right margin  
    // Set head 
    for(int i=0;i<fileHeader.length;){
      c = r.createCell(i);
      c.setCellStyle(styleHeader);
      c.setCellValue(fileHeader[i]);
      i++;
    }
    // Set the content 
    for(int rownum=0;rownum<datas.size();){ //  line  row  datas.size()
      r = s.createRow(rownum+1); // Create a line 
      for(int cellnum=0;cellnum<fileHeader.length;){
        c = r.createCell(cellnum);
        c.setCellValue(datas.get(rownum)[cellnum]);
        c.setCellStyle(styleContent);
        cellnum++;
      }
      rownum++;
    }
    FileOutputStream out = null;
    try {
      //  Create a file or folder , Write it in 
      if(FileUtil.createFile(new File(filePath))){
        out = new FileOutputStream(filePath);
        wb.write(out);
      }
      
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      try {
        //  Close the stream 
        if(out != null){
          out.flush();
          out.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    } 
  }
  /**
   *  read  excel  The file content 
   * @param filePath
   * @param sheetIndex
   */
  public static List<Map<String,String>> readExcel(String filePath,int sheetIndex){
    List<Map<String,String>> mapList = new ArrayList<Map<String,String>>();
    //  head 
    List<String> list = new ArrayList<String>();
    // 
    int cnt = 0;
    int idx = 0;
    try { 
      InputStream input = new FileInputStream(filePath); // Establishing the input stream  
      Workbook wb = null; 
      wb = new HSSFWorkbook(input); 
      //  To obtain sheet page 
      Sheet sheet = wb.getSheetAt(sheetIndex); 
      Iterator<Row> rows = sheet.rowIterator(); 
      while (rows.hasNext()) { 
        Row row = rows.next();
        Iterator<Cell> cells = row.cellIterator(); 
        Map<String,String> map = new HashMap<String,String>();
        if(cnt == 0){ //  His head into the list In the 
          while (cells.hasNext()) { 
            Cell cell = cells.next(); 
            if(isContainMergeCell(sheet)){
              cancelMergeCell(sheet);
            }
            list.add(getStringCellValue(cell));
          }
          cnt ++;
          continue;
        }else {
          while (cells.hasNext()) { 
            Cell cell = cells.next(); 
            if(isContainMergeCell(sheet)){
              cancelMergeCell(sheet);
            }
            //  Distinguish the same head 
            list = ListUtil.changeSameVal(list); 
            map.put(list.get(idx++), getStringCellValue(cell));
          }
        }
        idx = 0;
        mapList.add(map);
      } 
      return mapList;
    } catch (IOException ex) { 
      ex.printStackTrace(); 
    }
    return null;
  }
  /**
   *  Merge cell 
   * @param sheet   The current sheet page 
   * @param firstRow  Start line 
   * @param lastRow  End line 
   * @param firstCol  Start column 
   * @param lastCol  The end of the column 
   */
  public static int mergeCell(Sheet sheet,int firstRow,int lastRow,int firstCol,int lastCol){
    if(sheet == null){
      return -1;
    }
    return sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
  }
  /**
   *  Cancel the merge cell 
   * @param sheet
   * @param idx
   */
  public static void cancelMergeCell(Sheet sheet){
    int sheetMergeCount = sheet.getNumMergedRegions();
    for(int idx = 0; idx < sheetMergeCount;){
      CellRangeAddress range = sheet.getMergedRegion(idx);
      String val = getMergeCellValue(sheet,range.getFirstRow(),range.getLastRow());
      //  Cancel the merge cell 
      sheet.removeMergedRegion(idx);
      for(int rownum=range.getFirstRow();rownum<range.getLastRow()+1;){
        for(int cellnum=range.getFirstColumn();cellnum<range.getLastColumn()+1;){
          sheet.getRow(rownum).getCell(cellnum).setCellValue(val);
          cellnum ++;
        }
        rownum ++;
      }
      idx++;
    }
  }
  /**
   *  Determines whether the specified cell is a merged cell 
   * @param sheet   The current sheet page 
   * @param firstRow  Start line 
   * @param lastRow  End line 
   * @param firstCol  Start column 
   * @param lastCol  The end of the column 
   * @return
   */
  public static boolean isMergeCell(Sheet sheet,
      int row ,int column){
    int sheetMergeCount = sheet.getNumMergedRegions();
    for(int i = 0; i < sheetMergeCount;){
      CellRangeAddress range = sheet.getMergedRegion(i);
      int firstColumn = range.getFirstColumn(); 
      int lastColumn = range.getLastColumn(); 
      int firstRow = range.getFirstRow(); 
      int lastRow = range.getLastRow();
      if(row >= firstRow && row <= lastRow){
        if(column >= firstColumn && column <= lastColumn){ 
          return true; 
        } 
      }
      i++;
    }
    return false;
  }
  /**
   *  judge sheet Page contains merged cells 
   * @param sheet
   * @return
   */
  public static boolean isContainMergeCell(Sheet sheet){
    if(sheet == null){
      return false;
    }
    return sheet.getNumMergedRegions()>0 ? true : false;
  }
  /**
   *  Gets the value of the specified merge unit 
   * @param sheet
   * @param row
   * @param column
   * @return
   */
  public static String getMergeCellValue(Sheet sheet,
      int row ,int column){
    int sheetMergeCount = sheet.getNumMergedRegions();
    for(int i = 0; i < sheetMergeCount;){
      CellRangeAddress range = sheet.getMergedRegion(i);
      int firstColumn = range.getFirstColumn(); 
      int lastColumn = range.getLastColumn(); 
      int firstRow = range.getFirstRow(); 
      int lastRow = range.getLastRow();
      if(row >= firstRow && row <= lastRow){
        if(column >= firstColumn && column <= lastColumn){ 
          Row fRow = sheet.getRow(firstRow);  
          Cell fCell = fRow.getCell(firstColumn);
          return getStringCellValue(fCell) ;  
        } 
      }
      i++;
    }
    return null;
  }
  /**
   *  Gets the value of the cell 
   * @param cell
   * @return
   */
  public static String getStringCellValue(Cell cell) { 
    String strCell = ""; 
    if(cell==null) return strCell; 
    switch (cell.getCellType()) { 
      case Cell.CELL_TYPE_STRING:
        strCell = cell.getRichStringCellValue().getString().trim(); 
        break; 
      case Cell.CELL_TYPE_NUMERIC:  
        strCell = String.valueOf(cell.getNumericCellValue()); 
        break; 
      case Cell.CELL_TYPE_BOOLEAN:   
        strCell = String.valueOf(cell.getBooleanCellValue()); 
        break; 
      case Cell.CELL_TYPE_FORMULA:   
        FormulaEvaluator evaluator = cell.getSheet().getWorkbook().getCreationHelper().createFormulaEvaluator(); 
        evaluator.evaluateFormulaCell(cell); 
        CellValue cellValue = evaluator.evaluate(cell); 
        strCell = String.valueOf(cellValue.getNumberValue()) ; 
        break; 
      default: 
        strCell = ""; 
    } 
    return strCell; 
  }
}

This is called as follows

ExcelUtilTester.java


package pers.kangxu.datautils.test;
import java.util.ArrayList;
import java.util.List;
import pers.kangxu.datautils.utils.ExcelUtil;
public class ExcelUtilTester {
  public static void main(String[] args) {
    List<String[]> datas = new ArrayList<String[]>();
    datas.add(new String[]{" bear "," The mother ","250"});
    datas.add(new String[]{" The pig food "," unknown ","251"});
    //ExcelUtil.writeExcel("C:\\Users\\Administrator\\Desktop\\test\\test\\test.xls","sheet1",0, new String[]{" The name "," age "," gender "}, datas);
    System.out.println(ExcelUtil.readExcel("C:\\Users\\Administrator\\Desktop\\test\\test\\test.xls", 0));
  }
}

Related articles: