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

时间:2022-01-31 22:49:22

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
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包:

?
1
2
3
4
5
6
<!-- poi excel 文件读写 -->
   <dependency>
     <groupid>org.apache.poi</groupid>
     <artifactid>poi-excelant</artifactid>
     <version>3.14</version>
   </dependency>

准备需要读写的文件:

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

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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;
  }
?
1
2
3
4
5
6
<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>

最后数据库

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

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

原文链接:https://www.cnblogs.com/SimonHu1993/p/8202391.html