栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java读写Excel实例分享

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java读写Excel实例分享

话不多说,请看代码:

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;

public class ExcelUtil {
  
  public static void writeExcel(String filePath,String sheetName,
    int sheetIndex,
    String[] fileHeader,
    List datas){
    // 创建工作簿
    Workbook wb = new HSSFWorkbook();
    // 创建工作表 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;
    //粗体 
    font = wb.createFont(); 
    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
    // 设置头样式
    styleHeader = wb.createCellStyle(); 
    styleHeader.setFont(font); 
    styleHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框  
    styleHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框  
    styleHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框  
    styleHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 
    // 设置内容样式
    styleContent = wb.createCellStyle();
    styleContent.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框  
    styleContent.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框  
    styleContent.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框  
    styleContent.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框 
    //设置头
    for(int i=0;i> readExcel(String filePath,int sheetIndex){
    List> mapList = new ArrayList>();
    // 头
    List list = new ArrayList();
    // 
    int cnt = 0;
    int idx = 0;
    try { 
      InputStream input = new FileInputStream(filePath); //建立输入流 
      Workbook wb = null; 
      wb = new HSSFWorkbook(input); 
      // 获取sheet页
      Sheet sheet = wb.getSheetAt(sheetIndex); 
      Iterator rows = sheet.rowIterator(); 
      while (rows.hasNext()) { 
 Row row = rows.next();
 Iterator cells = row.cellIterator(); 
 Map map = new HashMap();
 if(cnt == 0){ // 将头放进list中
   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);
     }
     // 区别相同的头
     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;
  }
  
  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));
  }
  
  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());
      // 取消合并单元格
      sheet.removeMergedRegion(idx);
      for(int rownum=range.getFirstRow();rownum= firstRow && row <= lastRow){
 if(column >= firstColumn && column <= lastColumn){ 
   return true; 
 } 
      }
      i++;
    }
    return false;
  }
  
  public static boolean isContainMergeCell(Sheet sheet){
    if(sheet == null){
      return false;
    }
    return sheet.getNumMergedRegions()>0 ? true : false;
  }
  
  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;
  }
  
  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; 
  }
}

调用方式如下

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 datas = new ArrayList();
    datas.add(new String[]{"狗熊","母","250"});
    datas.add(new String[]{"猪粮","不明","251"});
    //ExcelUtil.writeExcel("C:\Users\Administrator\Desktop\test\test\test.xls","sheet1",0, new String[]{"姓名","年龄","性别"}, datas);
    System.out.println(ExcelUtil.readExcel("C:\Users\Administrator\Desktop\test\test\test.xls", 0));
  }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/148189.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号