liuxiaolong
2019-05-09 0d1d88cdb668e75ea8609417ac18ae19947e9525
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
 
 
package framework.util.excel;
 
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 
/**
 * poi 3.6
 * 
 * @author liuyajun
 * @date 2013-10-23 上午09:35:09
 */
public final class ExcelReader {
 
    /**
     * 日期类型
     */
    protected SimpleDateFormat[] dateFmt = new SimpleDateFormat[]{
            //new SimpleDateFormat("yyyy-MM"),
            //new SimpleDateFormat("yyyy-MM-dd"),
            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
            //new SimpleDateFormat("HH:mm:ss")
    };
    
    protected ExcelReader(){
        
    }
    /**
     * 打开 *.xls (Excel 2003)
     * 
     * @param f
     * @return
     * @throws Exception
     */
    public static ExcelReader open(File f) throws Exception {
        ByteArrayOutputStream byteOS = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(f);
        byte[] by = new byte[512];
        int t = fis.read(by, 0, by.length);
        while (t > 0) {
            byteOS.write(by, 0, 512);
            // 这里别写成t,写够512,呵呵,SB的方法对付SB的java API
            t = fis.read(by, 0, by.length);
        }
        byteOS.close();
        fis.close();
        
        ExcelReader reader = new ExcelReader();
        
        reader.bais = new ByteArrayInputStream(byteOS.toByteArray());
        reader.book = new HSSFWorkbook(reader.bais);
 
        if (reader.book == null) {
            fis.close();
        }
        return reader;
    }
 
    protected ByteArrayInputStream bais;
    protected HSSFWorkbook book;
 
    /**
     * 得到所有 sheet 名称
     * 
     * @return
     */
    public String[] getSheets() {
        int len = book.getNumberOfSheets();
        String[] name = new String[len];
        for (int i = 0; i < len; i++) {
            name[i] = book.getSheetName(i);
        }
        return name;
    }
    /**
     * 根据 sheetName 得到内容
     * @param sheetName
     * @return 可能为null, 每行的列数可能不同
     */
    public String[][] getData(String sheetName){
        return this.getData(sheetName, Integer.MAX_VALUE, Integer.MAX_VALUE);
    }
    /**
     * 根据 sheetName 得到内容
     * 
     * @param sheetName
     * @param rows    最多行数
     * @param cols    最多列数
     * @return     可能为null, 每行的列数可能不同
     */
    public String[][] getData(String sheetName, int rows, int cols) {
        int sheetId = book.getSheetIndex(sheetName);
        if(sheetId<0){
            return null;
        }
 
        HSSFSheet sheet = book.getSheetAt(sheetId);
        int rowNum = sheet.getPhysicalNumberOfRows();    //最大已用行数
        if(rows<rowNum){
            rowNum = rows;
        }
        if(rowNum<=0){
            return null;
        }
        String[][] s = new String[rowNum][];
        
        for (int i = 0; i < rowNum; i++) {
            HSSFRow rowData = sheet.getRow(i);
            if(rowData==null){
                s[i] = new String[0];
                continue;
            }
            int colNum = rowData.getPhysicalNumberOfCells();    //列,会多一空白列
            if(cols<colNum){
                colNum = cols;
            }
            if(colNum<=0){
                s[i] = new String[0];
                continue;
            }
            
            String[] ss = new String[colNum];
            for (int j = 0; j < colNum; j++) {
                ss[j] = "";
                
                try {
                    HSSFCell cell = rowData.getCell(j);
                    
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_STRING:        //字符串
                        ss[j] = cell.getStringCellValue();//.replaceAll("'", "''");
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            //时间日期
                            for(SimpleDateFormat fmt : dateFmt){
                                try{
                                    ss[j] = fmt.format(cell.getDateCellValue());
                                    break;
                                }catch(Exception e){
                                    
                                }
                            }
                        } else {
                            //数字
                            ss[j] = getDoubleString(cell.getNumericCellValue());
                        }
                        break;
                    default:
                        ss[j] = "";
                        break;
                    }
                } catch (Exception e) {
                    ss[j] = "";
                }
                ss[j] = ss[j].trim();
 
            }
            s[i] = ss;
        }
        return s;
    }
    protected DecimalFormat df = new DecimalFormat(
    "#.00000000000000000000000000000000000000000000000000000000000000000000");
    
    protected String getDoubleString(double d){
        String s = df.format(d);
        s = s.replaceAll("[0]*$", "");
        s = s.replaceAll("[.]$", "");
 
        return s;
    }
    /**
     * 关闭
     * 
     */
    public void close() throws Exception {
        bais.close();
    }
    
    public static void main(String[] args) throws Exception {
        String f = "e:/mm.xls";
        
        ExcelReader r = ExcelReader.open(new File(f));
        String[] a=r.getSheets();
        String[][] s = r.getData("Sheet1");
        
        for(int i=0; i<s.length; i++){
            for(int j=0; j<s[i].length; j++){
                //System.err.print(i+", "+j+": ");
                //System.err.println(s[i][j]);
            }
        }
    }
}