java操作excel文件

这里用一个简单的例子来演示 java操作excel文件

用maven可以把包导入进来:

1
2
3
4
5

org.apache.poi
poi-ooxml
3.9

demo

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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
package com.example.demo.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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;

/**

  • 读取Excel

  • @author zengwendong
    */
    public class ReadExcelUtils {

    private Workbook wb;
    private Sheet sheet;
    private Row row;

    public ReadExcelUtils(String filepath) {
    if (filepath == null) {
    return;
    }

     try {
         InputStream is = new FileInputStream(filepath);
         String ext = filepath.substring(filepath.lastIndexOf("."));
         if (".xls".equals(ext)) {
             wb = new HSSFWorkbook(is);
         } else if (".xlsx".equals(ext)) {
             wb = new XSSFWorkbook(is);
         } else {
             wb = null;
         }
     } catch (FileNotFoundException e) {
         System.out.println(e.getLocalizedMessage() + "找不到文件");
     } catch (IOException e) {
         System.out.println(e.getMessage() + "io的异常");
     }
    

    }

    /**

    • 读取Excel表格表头的内容
    • @param InputStream
    • @return String 表头内容的数组
    • @author zengwendong
      */
      public String[] readExcelTitle() throws Exception {
      if (wb == null) {
      throw new Exception(“Workbook对象为空!”);
      }
      sheet = wb.getSheetAt(0);
      row = sheet.getRow(0);
      // 标题总列数
      int colNum = row.getPhysicalNumberOfCells();
      System.out.println(“colNum:” + colNum);
      String[] title = new String[colNum];
      for (int i = 0; i < colNum; i++) {
      // title[i] = getStringCellValue(row.getCell((short) i));
      title[i] = row.getCell(i).getCellFormula();
      }
      return title;
      }

    /**

    • 读取Excel数据内容

    • @param InputStream

    • @return Map 包含单元格数据内容的Map对象

    • @author zengwendong
      */
      public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
      if (wb == null) {
      throw new Exception(“Workbook对象为空!”);
      }
      Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();

      sheet = wb.getSheetAt(0);
      // 得到总行数
      int rowNum = sheet.getLastRowNum();
      row = sheet.getRow(0);
      int colNum = row.getPhysicalNumberOfCells();
      // 正文内容应该从第二行开始,第一行为表头的标题
      for (int i = 1; i <= rowNum; i++) {
      row = sheet.getRow(i);
      int j = 0;
      Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
      while (j < colNum) {
      Object obj = getCellFormatValue(row.getCell(j));
      cellValue.put(j, obj);
      j++;
      }
      content.put(i, cellValue);
      }
      return content;
      }

    /**
    *

    • 根据Cell类型设置数据

    • @param cell

    • @return

    • @author zengwendong
      */
      private Object getCellFormatValue(Cell cell) {
      Object cellvalue = “”;
      if (cell != null) {
      // 判断当前Cell的Type
      switch (cell.getCellType()) {
      case Cell.CELL_TYPE_NUMERIC:// 如果当前Cell的Type为NUMERIC
      case Cell.CELL_TYPE_FORMULA: {
      // 判断当前的cell是否为Date
      if (DateUtil.isCellDateFormatted(cell)) {
      // 如果是Date类型则,转化为Data格式
      // data格式是带时分秒的:2013-7-10 0:00:00
      // cellvalue = cell.getDateCellValue().toLocaleString();
      // data格式是不带带时分秒的:2013-7-10
      Date date = cell.getDateCellValue();
      cellvalue = date;
      } else {// 如果是纯数字

               // 取得当前Cell的数值
               cellvalue = String.valueOf(cell.getNumericCellValue());
           }
           break;
       }
       case Cell.CELL_TYPE_STRING:// 如果当前Cell的Type为STRING
           // 取得当前的Cell字符串
           cellvalue = cell.getRichStringCellValue().getString();
           break;
       default:// 默认的Cell值
           cellvalue = "";
       }
      

      } else {
      cellvalue = “”;
      }
      return cellvalue;
      }

    public static void main(String[] args) {
    try {
    String filepath = “F:user.xls”;
    ReadExcelUtils excelReader = new ReadExcelUtils(filepath);
    // 对读取Excel表格标题测试
    // String[] title = excelReader.readExcelTitle();
    // System.out.println(“获得Excel表格的标题:”);
    // for (String s : title) {
    // System.out.print(s + " ");
    // }
    // 对读取Excel表格内容测试
    Map<Integer, Map<Integer, Object>> map = excelReader.readExcelContent();
    System.out.println(“获得Excel表格的内容:”);
    for (int i = 1; i <= map.size(); i++) {
    System.out.println(map.get(i));
    }
    } catch (FileNotFoundException e) {
    System.out.println(“未找到指定路径的文件!”);
    e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值