当前位置: 移动技术网 > IT编程>开发语言>Java > java读写excel文件实现POI解析Excel的方法

java读写excel文件实现POI解析Excel的方法

2019年07月19日  | 移动技术网IT编程  | 我要评论
在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对excel中的数据进行读取操作,本文将介绍excel读写的常用方法,希望对大家学

在日常工作中,我们常常会进行文件读写操作,除去我们最常用的纯文本文件读写,更多时候我们需要对excel中的数据进行读取操作,本文将介绍excel读写的常用方法,希望对大家学习java读写excel会有帮助。

package com.zhx.base.utils;

import org.apache.poi.hssf.usermodel.hssfworkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.xssfworkbook;

import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.util.arraylist;
import java.util.list;

/**
 * poi解析excel
 */
public class excelreaderutil {

  /**
   * 根据filetype不同读取excel文件
   *
   * @param path
   * @param path
   * @throws ioexception
   */
  public static list<list<string>> readexcel(string path) {
    string filetype = path.substring(path.lastindexof(".") + 1);
    // return a list contains many list
    list<list<string>> lists = new arraylist<list<string>>();
    //读取excel文件
    inputstream is = null;
    try {
      is = new fileinputstream(path);
      //获取工作薄
      workbook wb = null;
      if (filetype.equals("xls")) {
        wb = new hssfworkbook(is);
      } else if (filetype.equals("xlsx")) {
        wb = new xssfworkbook(is);
      } else {
        return null;
      }

      //读取第一个工作页sheet
      sheet sheet = wb.getsheetat(0);
      //第一行为标题
      for (row row : sheet) {
        arraylist<string> list = new arraylist<string>();
        for (cell cell : row) {
          //根据不同类型转化成字符串
          cell.setcelltype(cell.cell_type_string);
          list.add(cell.getstringcellvalue());
        }
        lists.add(list);
      }
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      try {
        if (is != null) is.close();
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return lists;
  }


  /**
   * 创建excel.xls
   * @param lists 需要写入xls的数据
   * @param titles 列标题
   * @param name 文件名
   * @return
   * @throws ioexception
   */
  public static workbook createxcel(list<list<string>> lists, string[] titles, string name) throws ioexception {
    system.out.println(lists);
    //创建新的工作薄
    workbook wb = new hssfworkbook();
    // 创建第一个sheet(页),并命名
    sheet sheet = wb.createsheet(name);
    // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
    for(int i=0;i<titles.length;i++){
      sheet.setcolumnwidth((short) i, (short) (35.7 * 150));
    }

    // 创建第一行
    row row = sheet.createrow((short) 0);

    // 创建两种单元格格式
    cellstyle cs = wb.createcellstyle();
    cellstyle cs2 = wb.createcellstyle();

    // 创建两种字体
    font f = wb.createfont();
    font f2 = wb.createfont();

    // 创建第一种字体样式(用于列名)
    f.setfontheightinpoints((short) 10);
    f.setcolor(indexedcolors.black.getindex());
    f.setboldweight(font.boldweight_bold);

    // 创建第二种字体样式(用于值)
    f2.setfontheightinpoints((short) 10);
    f2.setcolor(indexedcolors.black.getindex());

    // 设置第一种单元格的样式(用于列名)
    cs.setfont(f);
    cs.setborderleft(cellstyle.border_thin);
    cs.setborderright(cellstyle.border_thin);
    cs.setbordertop(cellstyle.border_thin);
    cs.setborderbottom(cellstyle.border_thin);
    cs.setalignment(cellstyle.align_center);

    // 设置第二种单元格的样式(用于值)
    cs2.setfont(f2);
    cs2.setborderleft(cellstyle.border_thin);
    cs2.setborderright(cellstyle.border_thin);
    cs2.setbordertop(cellstyle.border_thin);
    cs2.setborderbottom(cellstyle.border_thin);
    cs2.setalignment(cellstyle.align_center);
    //设置列名
    for(int i=0;i<titles.length;i++){
      cell cell = row.createcell(i);
      cell.setcellvalue(titles[i]);
      cell.setcellstyle(cs);
    }
    if(lists == null || lists.size() == 0){
      return wb;
    }
    //设置每行每列的值
    for (short i = 1; i <= lists.size(); i++) {
      // row 行,cell 方格 , row 和 cell 都是从0开始计数的
      // 创建一行,在页sheet上
      row row1 = sheet.createrow((short)i);
      for(short j=0;j<titles.length;j++){
        // 在row行上创建一个方格
        cell cell = row1.createcell(j);
        cell.setcellvalue(lists.get(i-1).get(j));
        cell.setcellstyle(cs2);
      }
    }
    return wb;
  }

  public static void main(string[] args) {
    string path = "d:/software/企发支付-员工信息表.xlsx";
    list<list<string>> lists = readexcel(path);
    for (list<string> list : lists) {
      for (string strs : list) {
        system.out.println(strs);
      }
    }
  }
}

需要导入的jar包:

 <!-- poi excel 文件读写 -->
    <dependency>
      <groupid>org.apache.poi</groupid>
      <artifactid>poi-excelant</artifactid>
      <version>3.14</version>
    </dependency>

准备需要读写的文件:

上述工具类中将每行放到一个list中,然后每行的每列放入到一个list中,这里再根据自己需求去对表中数据进行处理:

我现在要取得企业名称(资和信***)和从第七行起开始的id、姓名、识别号存入数据库中,这边我只展示service层处理,mybatis进行批量插入:

public map insem(file file) throws filenotfoundexception {
    string companyname = "";
    string epid = "";
    list<map> listmap = new arraylist<>();
    list<list<string>> lists = excelreaderutil.readexcel(file.getpath());
    for (int j = 0; j < lists.size(); j++) {
      list list = lists.get(j);
      for (int i = 0; i < list.size(); i++) {
        if (list.get(i).equals("企业名称")) {
          companyname = list.get(i + 1).tostring();
          epid = employeemapper.selepid(companyname);
          break;
        } else if (list.get(i).equals("员工识别号")) {
          for (int m = j + 1; m < lists.size() - 1; m++) {
            map map = new hashmap();
            if (null != lists.get(m) && lists.get(m).size() > 0) {
              list datalist = lists.get(m);
              map.put("id", datalist.get(0));
              map.put("epid", epid);
              map.put("name", datalist.get(1));
              map.put("identify", datalist.get(2));
              listmap.add(map);
            }
          }
        }
      }
    }
    map datamap = new hashmap();
    datamap.put("employees", listmap);
    employeemapper.insem(datamap);
    return null;
  }
<insert id="insem" parametertype="java.util.map">
    insert into qf_employee_info(epid,employee_id,user_name,phone,user_email,status,create_time,creater,create_type) value
    <foreach collection="employees" index="index" item="item" separator=",">
      (#{item.epid},"",#{item.name},#{item.identify},"",1,now(),"",2)
    </foreach>
  </insert>

最后数据库

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

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网