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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
 
package framework.util.excel;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.util.CellRangeAddress;
/**
 * poi 3.6
 * jdk1.4
 */
public final class ExcelWriter {
    
    public static final int STYLE_BORDER = 0X01;
    public static final int STYLE_BACK_GRAY = 0x02;
    public static final int STYLE_BACK_YELLOW = 0x04;
    
    public static final int STYLE_ALIGN_LEFT = 0x0100;
    public static final int STYLE_ALIGN_CENTER = 0x0200;
    public static final int STYLE_ALIGN_RIGHT = 0x0400;
    
    public static final int MAX_ROWS = 65500;
    
    private ExcelWriter(){
        
    }
    private static String modulePath = null;
    
    /**
     * 设置模板路径
     * @param path
     */
    public static void setModulePath(String path){
        if(path.endsWith("/")){
            path = path.substring(0, path.length()-1);
        }
        modulePath = path;
    }
    private static String downloadPath = null;
    /**
     * 设置生成路径
     * @param path
     */
    public static void setTempPath(String path){
        if(path.endsWith("/")){
            path = path.substring(0, path.length()-1);
        }
        downloadPath = path;
    }
    protected static Map<String, byte[]> moduleMap = new HashMap<String, byte[]>();
    
    protected static byte[] getModuleContent(String moduleName) 
            throws Exception {
        byte[] b = (byte[])moduleMap.get(moduleName);
        if(b==null){
            synchronized(moduleMap){
                b = (byte[])moduleMap.get(moduleName);
                if(b==null){
                    String moduleFileName = modulePath +"/"+moduleName;
                    FileInputStream fis = null;
                    try{
                        fis = new FileInputStream(moduleFileName);
                        b = new byte[fis.available()];
                        fis.read(b);
                        moduleMap.put(moduleName, b);
                    }catch(Exception e){
                        throw e;
                    }finally{
                        try{
                            fis.close();
                        }catch(Exception e){
                            
                        }
                    }
                }
            }
        }
        return b;
    }
    static {
        String moduleName = "blank.xls";
        InputStream is = ExcelWriter.class.getResourceAsStream(moduleName);
        try{
            byte[] b = new byte[is.available()];
            is.read(b);
            moduleMap.put(moduleName, b);
        }catch(Exception e){
 
        }finally{
            try{
                is.close();
            }catch(Exception e){
                
            }
        }
    }
    /**
     * 使用默认模板创建Writer
     * @param fileName
     * @return
     * @throws Exception
     */
    public static ExcelWriter open(String fileName) throws Exception {
        return open(fileName, "blank");
    }
    private static SimpleDateFormat timeFmt = new SimpleDateFormat("yyyy-MM-dd_HHmmss.SSSS");
    /**
     * 使用模板创建Writer
     * @param fileName
     * @param moduleName
     * @return
     * @throws Exception
     */
    public static ExcelWriter open(String fileName, String moduleName) 
            throws Exception {
        ExcelWriter writer = new ExcelWriter();
        String time = "_"+timeFmt.format(new Date());
 
        fileName = fileName.replaceAll("[\r\n\\*?<>|/]", "");
        
        writer.fileName = downloadPath + "/" + fileName + time +".xls";
 
        FileOutputStream fos = null;
        try{
            fos = new FileOutputStream(writer.fileName);
            fos.write(getModuleContent(moduleName+".xls"));
            fos.flush();
        }catch(Exception e){
            throw e;
        }finally{
            fos.close();
        }
        
        writer.fis = new FileInputStream(writer.fileName);
        writer.book = new HSSFWorkbook(writer.fis);
        
        writer.dateStyle = writer.book.createCellStyle();
        writer.dateStyle.setDataFormat(writer.book.createDataFormat()
                .getFormat("yyyy-mm-dd"));
 
        writer.timeStyle = writer.book.createCellStyle();
        writer.timeStyle.setDataFormat(writer.book.createDataFormat()
                .getFormat("hh:mm:ss"));
        
        writer.datetimeStyle = writer.book.createCellStyle();
        writer.datetimeStyle.setDataFormat(writer.book.createDataFormat()
                .getFormat("yyyy-mm-dd hh:mm:ss"));
        
        writer.monthStyle = writer.book.createCellStyle();
        writer.monthStyle.setDataFormat(writer.book.createDataFormat()
                .getFormat("yyyy-mm"));
 
        writer.sheet = null;    //初始没有sheet
        
        return writer;
    }
 
    protected String fileName;
    protected FileInputStream fis;
    protected HSSFWorkbook book;
    protected HSSFCellStyle monthStyle;
    protected HSSFCellStyle dateStyle;
    protected HSSFCellStyle timeStyle;
    protected HSSFCellStyle datetimeStyle;
    
    protected HSSFSheet sheet;
    
    /**
     * 冻结窗口
     * @param row    从0开始
     * @param col    从0开始
     */
    public ExcelWriter freeze(int row, int col){
        if(sheet!=null){
            sheet.createFreezePane(col, row);
        }
        return this;
    }
    /**
     * 删除sheet
     * 
     * @param sheetName
     */
    public ExcelWriter deleteSheet(String sheetName){
        try{
            if(sheetName!=null){
                book.removeSheetAt(book.getSheetIndex(sheetName));
            }
        }catch(Throwable e){
            
        }
        return this;
    }
    /**
     * 转到sheet
     * 
     * @param sheetName
     */
    public ExcelWriter setSheet(String sheetName){
        if(sheetName == null){
            sheet = book.getSheetAt(0);
        }else{
            sheet = book.getSheet(sheetName);
            if(sheet == null){
                int len = book.getNumberOfSheets();
                String s = ""+len+(new Date()).getTime();
                sheet = book.createSheet(s);
                book.setSheetName(book.getSheetIndex(s), sheetName);
            }
            book.setActiveSheet(book.getSheetIndex(sheetName));
        }
        return this;
    }
    /**
     * 复制sheet并选择新sheet
     * @param src
     * @param des
     * @return
     * @throws Exception
     */
    public ExcelWriter copySheet(String src, String des) {
        HSSFSheet sh = book.cloneSheet(book.getSheetIndex(src));
        String sn = sh.getSheetName();
        book.setSheetName(book.getSheetIndex(sn), des);
        sheet = sh;
        return this;
    }
    /**
     * 自动适应列
     * 
     * @param col
     * @return
     */
    public ExcelWriter autoSize(int col){
        if(sheet!=null){
            sheet.autoSizeColumn(col);
        }
        return this;
    }
    /**
     * 得到单元格
     * 
     * @param row 从0开始
     * @param col    从0开始
     * @return
     */
    public HSSFCell getCell(int row, int col){
        if(sheet == null){
            setSheet(null);
        }
        HSSFRow curRow = sheet.getRow(row);
        if(curRow == null){
            curRow = sheet.createRow(row);
        }
        HSSFCell cell = curRow.getCell(col);
        if(cell == null){
            cell = curRow.createCell(col);
        }
 
//        cell.setEncoding(HSSFCell.ENCODING_UTF_16);
        return cell;
    }
    
    /**
     * 合并单元格
     * 
     * @param row1
     * @param col1
     * @param row2
     * @param col2
     * @return
     */
    public ExcelWriter margeCell(int row1, int col1, int row2, int col2){
        CellRangeAddress region = new CellRangeAddress(row1, row2, col1, col2);
        sheet.addMergedRegion(region);
        return this;
    }
 
    /**
     * 设置样式
     * 
     * @param row
     * @param col
     * @param style
     * @return
     */
    public ExcelWriter setCellStyle(int row, int col, int style){
        HSSFCellStyle s = book.createCellStyle();
 
        if((style & STYLE_BORDER)==STYLE_BORDER){
            s.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            s.setBorderTop(HSSFCellStyle.BORDER_THIN);
            s.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            s.setBorderRight(HSSFCellStyle.BORDER_THIN);
        }
        if((style & STYLE_BACK_GRAY)==STYLE_BACK_GRAY){
            s.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
            s.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        }
        if((style & STYLE_BACK_YELLOW)==STYLE_BACK_YELLOW){
            s.setFillForegroundColor(HSSFColor.YELLOW.index);
            s.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        }
 
        if((style & STYLE_ALIGN_LEFT)==STYLE_ALIGN_LEFT){
            s.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        }else if((style & STYLE_ALIGN_RIGHT)==STYLE_ALIGN_RIGHT){
            s.setAlignment(HSSFCellStyle.ALIGN_RIGHT);
        }else if((style & STYLE_ALIGN_CENTER)==STYLE_ALIGN_CENTER){
            s.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        }
        this.getCell(row, col).setCellStyle(s);
        
        return this;
    }
    /**
     * 以 STYLE_BACK_GRAY|STYLE_BORDER 样式填充
     * @param row
     * @param col
     * @param s
     * @return
     */
    public ExcelWriter setTitle(int row, int col, String s){
        this.setCellStyle(row, col, STYLE_BACK_GRAY|STYLE_BORDER);
        this.setCellValue(row, col, s);
        this.autoSize(col);
        return this;
    }
    /**
     * 以STYLE_BACK_GRAY|STYLE_BORDER样式填充第一行,并冻结
     * @param s
     * @return
     */
    public ExcelWriter setTitle(String[] s){
        for(int i=0; i<s.length; i++){
            setTitle(0,i,s[i]);
        }
        this.freeze(1, 0);
        return this;
    }
    public ExcelWriter setCellValue(int row, int col, String str) {
        getCell(row, col).setCellValue(str==null?"":str);
        return this;
    }
 
    public ExcelWriter setCellValue(int row, int col, Integer d) {
        if(d!=null){
            getCell(row, col).setCellValue(d);
        }
        return this;
    }
    public ExcelWriter setCellValue(int row, int col, Long d) {
        if(d!=null){
            getCell(row, col).setCellValue(d);
        }
        return this;
    }
    public ExcelWriter setCellValue(int row, int col, Double d) {
        if(d!=null){
            getCell(row, col).setCellValue(d);
        }
        return this;
    }
    /**
     * yyyy-MM-dd
     * 
     * @param row
     * @param col
     * @param date
     * @return
     */
    public ExcelWriter setCellValue(int row, int col, Date date) {
        HSSFCell cell = getCell(row, col);
        cell.setCellStyle(dateStyle);
        if(date!=null){
            cell.setCellValue(date);
        }
        return this;
    }
    /**
     * yyyy-MM-dd HH:mm:ss
     * 
     * @param row
     * @param col
     * @param date
     * @return
     */
    public ExcelWriter setCellValueDatetime(int row, int col, Date date) {
        HSSFCell cell = getCell(row, col);
        cell.setCellStyle(datetimeStyle);
        if(date!=null){
            cell.setCellValue(date);
        }
        return this;
    }
    /**
     * HH:mm:ss
     * 
     * @param row
     * @param col
     * @param date
     * @return
     */
    public ExcelWriter setCellValueTime(int row, int col, Date date) {
        HSSFCell cell = getCell(row, col);
        cell.setCellStyle(timeStyle);
        if(date!=null){
            cell.setCellValue(date);
        }
        return this;
    }
    /**
     * yyyy-MM
     * 
     * @param row
     * @param col
     * @param date
     * @return
     */
    public ExcelWriter setCellValueMonth(int row, int col, Date date) {
        HSSFCell cell = getCell(row, col);
        cell.setCellStyle(monthStyle);
        if(date!=null){
            cell.setCellValue(date);
        }
        return this;
    }
 
    /**
     * 关闭,生成文件
     * 
     */
    public void saveAndClose() throws Exception {
        FileOutputStream fos = new FileOutputStream(fileName);
        book.write(fos);
        fos.flush();
        fos.close();
        fis.close();
    }
    /**
     * 得到生成的文件
     * 
     * @return
     */
    public File getFile(){
        return new File(fileName);
    }
    
    public static void main(String[] args) throws Exception{
        ExcelWriter.setTempPath("f:/");
        //System.err.println(moduleMap);
        ExcelWriter w = ExcelWriter.open("测试");
        w.setSheet("sheet1");
        w.setTitle(new String[]{
            "序号","姓\n名","地址"
        });
        w.saveAndClose();
    }
    public final HSSFWorkbook getBook() {
        return book;
    }
    public final HSSFSheet getSheet() {
        return sheet;
    }
}