欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java利用POI读写Excel文件工具类

程序员文章站 2024-01-09 23:59:46
本文实例为大家分享了java读写excel文件工具类的具体代码,供大家参考,具体内容如下package com.test.app.utils; import java.io.file;import j...

本文实例为大家分享了java读写excel文件工具类的具体代码,供大家参考,具体内容如下

package com.test.app.utils;
 
import java.io.file;
import java.io.fileinputstream;
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.list;
 
import org.apache.poi.hssf.usermodel.hssfdateutil;
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.usermodel.xssfworkbook;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.util.collectionutils;
 
/**
 * @description: excel读写工具类
 * @author: hunger.zhu
 * @createdate: 2019/4/10 13:21
 */
public class excelutils {
 
  private static final logger logger = loggerfactory.getlogger(excelutils.class);
 
  /**
   * 读取excel内容
   * @param file 需要被读的文件对象
   * @param startrow 从哪一行开始读 (rowindex从0开始的)
   * @param isexcel2003  是否是excel2003还是更高的版本
   * @param sheetindex  读取哪一个sheet (sheetindex也是从0开始)
   * @return list<list<string>>
   * @throws exception
   */
  public static list<list<string>> readexcel(file file, int startrow, boolean isexcel2003, int sheetindex) throws exception {
    list<list<string>> datalst;
    inputstream is = null;
    try {
      /** 创建读取文件的输入流 */
      is = new fileinputstream(file);
      /** 根据版本选择创建workbook的方式 */
      workbook wb;
      if (isexcel2003) {
        wb = new hssfworkbook(is);
      } else {
        wb = new xssfworkbook(is);
      }
      /** 调用本类的读取方法读取excel数据 */
      datalst = read(wb, startrow, sheetindex);
    } catch (exception ex) {
     logger.error("读取excel文件异常!", ex);
      ex.printstacktrace();
      throw ex;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (ioexception e) {
          e.printstacktrace();
        }
      }
    }
    /** 返回最后读取的结果 */
    return datalst;
  }
 
  private static list<list<string>> read(workbook wb, int startrow, int sheetindex) {
    /** 总列数 */
    int totalcells = 0;
   /** 创建集合存储读取的数据 */
    list<list<string>> datalst = new arraylist<list<string>>();
    /** 得到第一个shell */
    sheet sheet = wb.getsheetat(sheetindex);
    /** 得到excel的行数 */
    int totalrows = sheet.getphysicalnumberofrows();
    /** 得到excel的列数 */
    if (totalrows >= 1 && sheet.getrow(0) != null) {
      totalcells = sheet.getrow(0).getphysicalnumberofcells();
    }
    /** 循环excel的行 */
    for (int r = startrow; ; r++) {
      row row = sheet.getrow(r);
      if (row == null) {
        break;
      }
      list<string> rowlst = new arraylist<string>();
      /** 循环excel的列 */
      for (int c = 0; c < totalcells; c++) {
        cell cell = row.getcell(c);
        string cellvalue = "";
        if (null != cell) {
          // 以下是判断数据的类型
          switch (cell.getcelltypeenum()) {
          case numeric: // 数字
           // 判断是不是日期格式
           if (hssfdateutil.iscelldateformatted(cell)) {
           cellvalue = cell.getdatecellvalue() + "";
   }else {
    cellvalue = cell.getnumericcellvalue() + "";
   }
            break;
          case string: // 字符串
            cellvalue = cell.getstringcellvalue();
            break;
          case boolean: // boolean
            cellvalue = cell.getbooleancellvalue() + "";
            break;
          case formula: // 公式
            cellvalue = cell.getcellformula() + "";
            break;
          case blank: // 空值
            cellvalue = "";
            break;
          case error: // 故障
            cellvalue = "非法字符";
            break;
          default:
            cellvalue = "未知类型";
            break;
          }
        }
        rowlst.add(cellvalue);
      }
      /** 保存第r行的第c列 */
      boolean isemptyrow = true;
     
      if (rowlst != null) { 
       for (string s : rowlst) {
       if (s != null && !s.isempty()) {
        isemptyrow = false;
       }
       }
      }
      if (!isemptyrow) {
       datalst.add(rowlst);
      }
    }
    return datalst;
  }
 
  /**
   * 读取excel内容
   * @param filepath 被读取文件的绝对路径
   * @param startrow
   * @param isexcel2003
   * @param sheetindex
   * @return list<list<string>>
   * @throws exception
   */
  public static list<list<string>> readexcel(string filepath, int startrow, boolean isexcel2003, int sheetindex) throws exception {
   
   return readexcel(new file(filepath) , startrow, isexcel2003, sheetindex);
  }
 
  /**
   * 将数据写入excel工作簿
   * @param header  表格的标题
   * @param datalist 所需写入的数据 list<list<string>>
   * @param isexcel2003  是否是excel2003还是更高的版本
   * @param sheetname   生成的excel中sheet的名字
   * @return workbook  之后直接写出即可,如workbook.write(new fileoutputstream("e://test/20190410_test.xlsx"));
   */
  public static workbook getworkbookfromlist(list<string> header, list<list<string>> datalist, boolean isexcel2003,
                       string sheetname) {
    workbook wb;
    // 创建workbook对象(excel的文档对象)
    if (isexcel2003) {
      wb = new hssfworkbook();
    } else {
      wb = new xssfworkbook();
    }
    // 建立新的sheet对象(excel的表单)
    sheet sheet = wb.createsheet(sheetname);
    // 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
    int rownum = 0;
    row row0 = sheet.createrow(rownum);
    if (!collectionutils.isempty(header)) {
      // 设置表头
      for (int i = 0; i < header.size(); i++) {
        cell cell = row0.createcell(i);
        // 设置单元格样式
        cell.setcellstyle(poiutils.getcellstyle(wb, "calibri", (short) 12));
        // 设置列宽
        sheet.setcolumnwidth(i, 256 * 20);
        cell.setcellvalue(header.get(i));
      }
      rownum++;
    }
    if (!collectionutils.isempty(datalist)) {
      // 填充数据
      for (list<string> celllist : datalist) {
        row row = sheet.createrow(rownum);
        for (int i = 0; i < celllist.size(); i++) {
          cell cell = row.createcell(i);
          cell.setcellstyle(poiutils.getcellstyle(wb, "calibri", (short) 12));
          if (collectionutils.isempty(header)) {
            sheet.setcolumnwidth(i, 256 * 20);
          }
          cell.setcellvalue(celllist.get(i));
        }
        rownum++;
      }
    }
    return wb;
  }
 
  /**
   * 将数据写入excel工作簿
   * @param header  表格的标题
   * @param datalist 所需写入的数据 list<object>
   * @param isexcel2003  是否是excel2003还是更高的版本
   * @param sheetname   生成的excel中sheet的名字
   * @return workbook对象,之后直接写出即可,如workbook.write(new fileoutputstream("e://test/20190410_test.xlsx"));
   * @throws exception
   */
  public static workbook getworkbookfromobj(list<string> header, list<?> datalist, boolean isexcel2003,
                      string sheetname) throws exception {
    workbook wb;
    // 创建workbook对象(excel的文档对象)
    if (isexcel2003) {
      wb = new hssfworkbook();
    } else {
      wb = new xssfworkbook();
    }
    // 建立新的sheet对象(excel的表单)
    sheet sheet = wb.createsheet(sheetname);
    // 在sheet里创建第一行,参数为行索引(excel的行),可以是0~65535之间的任何一个
    int rownum = 0;
    row row0 = sheet.createrow(rownum);
    if (!collectionutils.isempty(header)) {
      // 设置表头
      for (int i = 0; i < header.size(); i++) {
        cell cell = row0.createcell(i);
        // 设置单元格样式
        cell.setcellstyle(poiutils.getcellstyle(wb, "calibri", (short) 12));
        sheet.setcolumnwidth(i, 256 * 20);
        cell.setcellvalue(header.get(i));
      }
      rownum++;
    }
    if (!collectionutils.isempty(datalist)) {
      // 填充数据
      class<? extends object> objclass = datalist.get(0).getclass();
      field[] fields = objclass.getdeclaredfields();
      for (int i = 0; i < datalist.size(); i++) {
        // 创建row对象
        row row = sheet.createrow(rownum);
        // 遍历获取每一个字段的值
        for (int j = 0; j < fields.length; j++) {
          string fieldval = "";
          method[] methods = objclass.getdeclaredmethods();
          for (method method : methods) {
            if (method.getname().equalsignorecase("get" + fields[j].getname())) {
              string property = (string) method.invoke(datalist.get(i), null);
              fieldval = property == null ? "" : property;
              break;
            }
          }
          cell cell = row.createcell(j);
          cell.setcellstyle(poiutils.getcellstyle(wb, "calibri", (short) 12));
          if (collectionutils.isempty(header)) {
            sheet.setcolumnwidth(j, 256 * 20);
          }
          cell.setcellvalue(fieldval);
        }
        rownum++;
      }
    }
    return wb;
  }
 
  public static boolean validateexcel(string filepath) {
    /** 检查文件名是否为空或者是否是excel格式的文件 */
    if (filepath == null
        || !(isexcel2003(filepath) || isexcel2007(filepath))) {
      // "文件名不是excel格式";
      return false;
    }
    /** 检查文件是否存在 */
    file file = new file(filepath);
    if (file == null || !file.exists()) {
      // "文件不存在";
      return false;
    }
    return true;
  }
  
  public static boolean isexcel2003(string filepath) {
    return filepath.matches("^.+\\.(?i)(xls)$");
  }
  
  public static boolean isexcel2007(string filepath) {
    return filepath.matches("^.+\\.(?i)(xlsx)$");
  }
 
}

以下为poiutils.java:

package com.test.app.utils;
 
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.font;
import org.apache.poi.xssf.usermodel.xssfcellstyle;
import org.apache.poi.xssf.usermodel.xssfcolor;
import org.apache.poi.xssf.usermodel.xssffont;
import org.apache.poi.xssf.usermodel.xssfworkbook;
 
import java.awt.*;
import java.awt.color;
 
/**
 * @description: excel的单元格样式
 * @author: hunger.zhu
 * @createdate: 2019/4/10 13:05
 */
public class poiutils {
 
 /**
 * 设置单元格的边框(细)且为黑色,字体水平垂直居中,自动换行
 * @param workbook
 * @param fontname
 * @param fontsize
 * @return
 */
  public static cellstyle getcellstyle(workbook workbook, string fontname, short fontsize){
    cellstyle style = workbook.createcellstyle();
    font font = workbook.createfont();
     // 设置上下左右四个边框宽度
     style.setbordertop(borderstyle.thin);
     style.setborderbottom(borderstyle.thin);
     style.setborderleft(borderstyle.thin);
     style.setborderright(borderstyle.thin);
     // 设置上下左右四个边框颜色
     style.settopbordercolor(indexedcolors.black.getindex());
     style.setbottombordercolor(indexedcolors.black.getindex());
     style.setleftbordercolor(indexedcolors.black.getindex());
     style.setrightbordercolor(indexedcolors.black.getindex());
     // 水平居中,垂直居中,自动换行
     style.setalignment(horizontalalignment.center);
     style.setverticalalignment(verticalalignment.center);
     style.setwraptext(false);
     // 设置字体样式及大小
     font.setfontname(fontname);
     font.setfontheightinpoints(fontsize);
     
     style.setfont(font);
     
     return style;
  }
 
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

相关标签: java 读写 Excel