加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java操作Excle(基于Poi)

发布时间:2020-12-15 07:52:10 所属栏目:Java 来源:网络整理
导读:有一次有个同事问我会不会有java操作Excle,回答当然是不会了!感觉被嘲讽了,于是开始寻找度娘,找到个小例子,结果越写越有意思,最后就成就了这个工具类。 1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.File; 4

有一次有个同事问我会不会有java操作Excle,回答当然是不会了!感觉被嘲讽了,于是开始寻找度娘,找到个小例子,结果越写越有意思,最后就成就了这个工具类。

  1 import java.io.BufferedReader;
  2 import java.io.BufferedWriter;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileNotFoundException;
  6 import java.io.FileOutputStream;
  7 import java.io.FileWriter;
  8 import java.io.IOException;
  9 import java.io.InputStream;
 10 import java.io.InputStreamReader;
 11 import java.io.OutputStream;
 12 import java.util.ArrayList;
 13 import java.util.Date;
 14 import java.util.HashSet;
 15 import java.util.Iterator;
 16 import java.util.List;
 17 import java.util.Map.Entry;
 18 import java.util.Set;
 19 
 20 import org.apache.poi.hssf.usermodel.HSSFCell;
 21 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 22 import org.apache.poi.hssf.usermodel.HSSFFont;
 23 import org.apache.poi.hssf.usermodel.HSSFRow;
 24 import org.apache.poi.hssf.usermodel.HSSFSheet;
 25 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 26 import org.apache.poi.hssf.util.HSSFColor;
 27 import org.apache.poi.ss.usermodel.BorderStyle;
 28 import org.apache.poi.ss.usermodel.Cell;
 29 import org.apache.poi.ss.usermodel.CellStyle;
 30 import org.apache.poi.ss.usermodel.DataFormat;
 31 import org.apache.poi.ss.usermodel.FillPatternType;
 32 import org.apache.poi.ss.usermodel.HorizontalAlignment;
 33 import org.apache.poi.ss.usermodel.IndexedColors;
 34 import org.apache.poi.ss.usermodel.Row;
 35 import org.apache.poi.ss.usermodel.Sheet;
 36 import org.apache.poi.ss.usermodel.VerticalAlignment;
 37 import org.apache.poi.ss.usermodel.Workbook;
 38 import org.apache.poi.ss.util.CellAddress;
 39 import org.apache.poi.xssf.usermodel.*;
 40 import org.apache.poi.xssf.usermodel.XSSFFont;
 41 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 42 
 43 /**
 44  * 
 45  * 这是一个对excle操作的类 有可以 读取 创建 修改
 46  * 
 47  * 对标题提供了基本的样式 包括 字体 背景颜色 边框 内容还未提供样式 后续处理吧
 48  * 
 49  * @author heyt
 50  * @param
 51  *
 52  */
 53 
 54 public class Excle {
 55 
 56     public static File excelFile;// 没有用该变量 后续一定变为用这个
 57 
 58     public static InputStream fileInStream;// 没有用该变量 后续一定变为用这个
 59 
 60     public static OutputStream fileOutStream;// 没有用该变量 后续一定变为用这个
 61 
 62     public static Workbook workBook;// 没有用该变量 后续一定变为用这个
 63 
 64     /**
 65      * 读取指定路径的Excel文件,并且按行获取数据记录到list中,最后返回结果为装有多行list对象的list数据。 即:一行数据装进一个list
 66      *
 67      * 注意:有几个sysout 输出语句是当时测试时候用的 如果将来这个方法处问题了 就解开观察一下
 68      * 
 69      * @param cFilePath
 70      * @return
 71      */
 72     public List<List<String>> readExcle(String cFilePath) {
 73         List<List<String>> sumLists = new ArrayList<List<String>>();
 74         List<String> sumList = null;
 75         boolean isE2007 = false; // 判断是否是excel2007格式
 76         if (cFilePath.endsWith(".xlsx"))
 77             isE2007 = true;
 78         try {
 79             InputStream input = new FileInputStream(cFilePath); // 建立输入流
 80             Workbook wb = null;
 81             // 根据文件格式(2003或者2007)来初始化
 82             if (isE2007)
 83                 wb = new XSSFWorkbook(input);
 84             else
 85                 wb = new HSSFWorkbook(input);
 86             Sheet sheet = wb.getSheetAt(0); // 获得第一个表单
 87             Iterator<Row> rows = sheet.rowIterator(); // 获得第一个表单的迭代器
 88             while (rows.hasNext()) {
 89                 Row row = rows.next(); // 获得行数据
 90                 Iterator<Cell> cells = row.cellIterator(); // 获得第一行的迭代器
 91                 // System.out.println("现在是读的第:" + row.getRowNum() + "行");
 92                 sumList = new ArrayList<String>();
 93                 // 遍历一行数据装到subList中
 94                 int count = 0;
 95                 int countRes = 0;
 96                 while (cells.hasNext()) {
 97                     Cell cell = cells.next();
 98                     // System.out.println("读取的第:" + cell.getColumnIndex() + "列" + ",应该写第:" +
 99                     // countRes + "列");
100                     count = cell.getColumnIndex();
101                     int res = count - countRes;
102                     // System.out.println("应该加:" + res + "列的空格");
103                     if (res == 0) {
104                         sumList.add(cell.toString());
105                         ++countRes;
106                     } else {
107                         for (int i = 0; i < res; i++) {
108                             sumList.add(" ");// 空位补空格
109                             ++countRes;
110                         }
111                         sumList.add(cell.toString());
112                         ++countRes;
113                     }
114                 }
115                 sumLists.add(sumList);
116             }
117         } catch (IOException ex) {
118             ex.printStackTrace();
119         }
120         return sumLists;
121     }
122     /**
123      * 根据一个excle的绝对路径,得到一个excle的所有sheet的名称保存到一个list里返回
124      * 
125      * @param cFilePath
126      * @return list<String>
127      */
128     public List<String> getSheetCountName(String cFilePath) {
129         List<String> sheetNames = new ArrayList<String>();
130         boolean isE2007 = false; // 判断是否是excel2007格式
131         if (cFilePath.endsWith(".xlsx"))
132             isE2007 = true;
133         try {
134             InputStream input = new FileInputStream(cFilePath); // 建立输入流
135             Workbook wb = null;
136             // 根据文件格式(2003或者2007)来初始化
137             if (isE2007)
138                 wb = new XSSFWorkbook(input);
139             else
140                 wb = new HSSFWorkbook(input);
141             int results = wb.getNumberOfSheets();
142             for (int i = 0; i < results; i++) {
143                 sheetNames.add(wb.getSheetName(i));
144             }
145             return sheetNames;
146         } catch (IOException ex) {
147             ex.printStackTrace();
148         }
149         return null;// 正常情况下永远都不会返回一个null吧
150     }
151     /**
152      * 这个是读一个exlce中的一个sheet,cFilePath是excle的绝对路径,
153      * index是sheet的下标,一般配合本类中的getSheetCountName()方法使用即可
154      */
155     public List<List<String>> readExcleOneSheet(String cFilePath,int index) {
156         List<List<String>> sumLists = new ArrayList<List<String>>();
157         List<String> sumList = null;
158         boolean isE2007 = false; // 判断是否是excel2007格式
159         if (cFilePath.endsWith(".xlsx"))
160             isE2007 = true;
161         try {
162             InputStream input = new FileInputStream(cFilePath); // 建立输入流
163             Workbook wb = null;
164             // 根据文件格式(2003或者2007)来初始化
165             if (isE2007)
166                 wb = new XSSFWorkbook(input);
167             else
168                 wb = new HSSFWorkbook(input);
169             Sheet sheet = wb.getSheetAt(index); // 获得第一个表单
170             Iterator<Row> rows = sheet.rowIterator(); // 获得第一个表单的迭代器
171             while (rows.hasNext()) {
172                 Row row = rows.next(); // 获得行数据
173                 Iterator<Cell> cells = row.cellIterator(); // 获得第一行的迭代器
174                 // System.out.println("现在是读的第:" + row.getRowNum() + "行");
175                 sumList = new ArrayList<String>();
176                 // 遍历一行数据装到subList中
177                 int count = 0;
178                 int countRes = 0;
179                 while (cells.hasNext()) {
180                     Cell cell = cells.next();
181                     // System.out.println("读取的第:" + cell.getColumnIndex() + "列" + ",应该写第:" +
182                     // countRes + "列");
183                     count = cell.getColumnIndex();
184                     int res = count - countRes;
185                     // System.out.println("应该加:" + res + "列的空格");
186                     if (res == 0) {
187                         sumList.add(cell.toString());
188                         ++countRes;
189                     } else {
190                         for (int i = 0; i < res; i++) {
191                             sumList.add(" ");// 空位补空格
192                             ++countRes;
193                         }
194                         sumList.add(cell.toString());
195                         ++countRes;
196                     }
197                 }
198                 sumLists.add(sumList);
199             }
200         } catch (IOException ex) {
201             ex.printStackTrace();
202         }
203         return sumLists;
204     }
205 
206     /**
207      * 对excle提供样式 说实话很简陋 哈哈
208      * 
209      * @param wb
210      * @param endStr
211      * @return
212      */
213     public static CellStyle initStyle(Workbook wb,final String endStr) {
214 
215         if (endStr.equals("xlsx")) {
216             XSSFCellStyle scs = (XSSFCellStyle) wb.createCellStyle();
217             scs.setAlignment(HorizontalAlignment.CENTER);// 居中
218             scs.setVerticalAlignment(VerticalAlignment.CENTER);
219 
220             scs.setBorderBottom(BorderStyle.THIN); // 下边框
221             scs.setBorderLeft(BorderStyle.THIN);// 左边框
222             scs.setBorderTop(BorderStyle.THIN);// 上边框
223             scs.setBorderRight(BorderStyle.THIN);// 右边框
224 
225             scs.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
226             scs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
227             scs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
228 
229             XSSFFont xf = (XSSFFont) wb.createFont();
230 
231             xf.setFontName("微软雅黑");
232             xf.setFontHeightInPoints((short) 10);
233 
234             scs.setFont(xf);
235             return scs;
236         }
237         if (endStr.equals("xls")) {
238 
239             HSSFCellStyle hcs = (HSSFCellStyle) wb.createCellStyle();
240             hcs.setAlignment(HorizontalAlignment.CENTER);// 居中
241             hcs.setVerticalAlignment(VerticalAlignment.CENTER);
242             hcs.setBorderBottom(BorderStyle.THIN); // 下边框
243             hcs.setBorderLeft(BorderStyle.THIN);// 左边框
244             hcs.setBorderTop(BorderStyle.THIN);// 上边框
245             hcs.setBorderRight(BorderStyle.THIN);// 右边框
246             hcs.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
247             hcs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
248             hcs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
249             HSSFFont hf = (HSSFFont) wb.createFont();
250             hf.setFontName("微软雅黑");
251             hf.setFontHeightInPoints((short) 10);
252 
253             hcs.setFont(hf);
254             return hcs;
255         }
256         return null;
257     }
258 
259     /**
260      * 对excle提供样式 说实话很简陋 哈哈
261      * 
262      * @param wb
263      * @param endStr
264      * @return
265      */
266     public static CellStyle initStyle2(Workbook wb,final String endStr) {
267 
268         if (endStr.equals("xlsx")) {
269             XSSFCellStyle scs = (XSSFCellStyle) wb.createCellStyle();
270             scs.setAlignment(HorizontalAlignment.LEFT);// 居中
271             scs.setVerticalAlignment(VerticalAlignment.CENTER);
272             scs.setBorderBottom(BorderStyle.THIN); // 下边框
273             scs.setBorderLeft(BorderStyle.THIN);// 左边框
274             scs.setBorderTop(BorderStyle.THIN);// 上边框
275             scs.setBorderRight(BorderStyle.THIN);// 右边框
276 
277             // scs.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
278             // scs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
279             // scs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
280 
281             XSSFFont xf = (XSSFFont) wb.createFont();
282             xf.setFontName("黑体");
283             xf.setFontHeightInPoints((short) 10);
284             scs.setFont(xf);
285             return scs;
286         }
287         if (endStr.equals("xls")) {
288 
289             HSSFCellStyle hcs = (HSSFCellStyle) wb.createCellStyle();
290             hcs.setAlignment(HorizontalAlignment.LEFT);// 居中
291             hcs.setVerticalAlignment(VerticalAlignment.CENTER);
292             hcs.setBorderBottom(BorderStyle.THIN); // 下边框
293             hcs.setBorderLeft(BorderStyle.THIN);// 左边框
294             hcs.setBorderTop(BorderStyle.THIN);// 上边框
295             hcs.setBorderRight(BorderStyle.THIN);// 右边框
296             // hcs.setFillForegroundColor(IndexedColors.BLUE.getIndex());
297             // hcs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
298             // hcs.setFillPattern(FillPatternType.SOLID_FOREGROUND);
299             HSSFFont hf = (HSSFFont) wb.createFont();
300             hf.setFontName("黑体");
301             hf.setFontHeightInPoints((short) 10);
302             hcs.setFont(hf);
303             return hcs;
304         }
305 
306         return null;
307     }
308 
309     /**
310      * @param filePath
311      *            文件路径
312      * @param str
313      *            表头的列名
314      * @param sheetName
315      *            顾名思义
316      * @return
317      */
318     public static boolean writeExcle(String filePath,String[] str,String sheetName) {
319 
320         String tFilePath = initFile(filePath);
321 
322         boolean bo = true;
323         Workbook wb = null;
324         CellStyle cs = null;
325         // 定义一个新的工作簿
326         if (tFilePath.endsWith(".xlsx")) {
327             wb = new XSSFWorkbook();
328             cs = initStyle(wb,"xlsx");
329         } else if (tFilePath.endsWith(".xls")) {
330             wb = new HSSFWorkbook();
331             cs = initStyle(wb,"xls");
332         } else
333             bo = false;
334         // 创建sheet1
335         Sheet sheet = wb.createSheet(sheetName);
336 
337         // 创建行
338         Row row = sheet.createRow(0);
339 
340         // DataFormat df= wb.createDataFormat();
341 
342         // scs.setDataFormat(df.getFormat("@"));
343 
344         for (int i = 0; i < str.length; i++) {
345 
346             // sheet.autoSizeColumn(i);//宽度自适应 亲测不管用
347 
348             row.createCell(i).setCellStyle(cs);
349             row.getCell(i).setCellValue(str[i]);// 创建单元格 表头
350 
351         }
352         // 写入
353         try {
354             FileOutputStream fileOutputStream = new FileOutputStream(tFilePath);
355             wb.write(fileOutputStream);
356             fileOutputStream.close();
357         } catch (IOException e) {
358             e.printStackTrace();
359         }
360 
361         return bo;
362     }
363 
364     /**
365      * @param filePath
366      *            文件路径
367      * @param str
368      *            表头的列名
369      * @param sheetName
370      *            顾名思义
371      * @param lis
372      *            填入exlce的数据
373      * @return
374      */
375     protected static boolean writeExcle(String filePath,String sheetName,List<List<String>> lis) {
376 
377         boolean bo = true;
378         Workbook wb = null;
379         String tFilePath = initFile(filePath);
380         CellStyle cs = null;
381         CellStyle cs2 = null;
382         // 定义一个新的工作簿
383         if (tFilePath.endsWith(".xlsx")) {
384             wb = new XSSFWorkbook();
385             cs = initStyle(wb,"xlsx");
386             cs2 = initStyle2(wb,"xlsx");
387         } else if (tFilePath.endsWith(".xls")) {
388             wb = new HSSFWorkbook();
389             cs = initStyle(wb,"xls");
390             cs2 = initStyle2(wb,"xls");
391         } else
392             bo = false;
393 
394         // 创建sheet1
395         Sheet sheet = wb.createSheet(sheetName);
396         // sheet.autoSizeColumn(0);//宽度自适应
397 
398         // 创建行
399         Row row = sheet.createRow(0);
400 
401         for (int k = 0; k < str.length; k++) {
402 
403             row.createCell(k).setCellValue(str[k]);// 创建单元格 表头
404             row.getCell(k).setCellStyle(cs);
405         }
406 
407         for (int i = 0; i < lis.size(); i++) {
408 
409             Row row2 = sheet.createRow(i + 1);
410 
411             for (int j = 0; j < lis.get(i).size(); j++) {
412 
413                 row2.createCell(j).setCellValue(lis.get(i).get(j).toString());
414 
415                 row2.getCell(j).setCellStyle(cs2);
416 
417                 // 这是不是应该也加一个样式呢 这就是个问题了 怎么完善呢 后续处理吧 initStyle2() return cellStyle;
418 
419             }
420         }
421 
422         // 写入
423         try {
424             FileOutputStream fileOutputStream = new FileOutputStream(tFilePath);
425             wb.write(fileOutputStream);
426             wb.close();
427             fileOutputStream.close();
428         } catch (IOException e) {
429             // TODO Auto-generated catch block
430             e.printStackTrace();
431         }
432 
433         return bo;
434     }
435 
436     public static boolean writeExcle(String filePath) {
437 
438         boolean bo = true;
439         Workbook wb = null;
440         String tFilePath = initFile(filePath);
441         // 定义一个新的工作簿
442         if (tFilePath.endsWith(".xlsx")) {
443             wb = new XSSFWorkbook();
444         } else if (tFilePath.endsWith(".xls"))
445             wb = new HSSFWorkbook();
446         else
447             bo = false;
448         // 创建sheet1
449         Sheet sheet = wb.createSheet("sheet1");
450 
451         // 创建行
452         Row row = sheet.createRow(0);
453 
454         // 写入
455         try {
456             FileOutputStream fileOutputStream = new FileOutputStream(tFilePath);
457             wb.write(fileOutputStream);
458             wb.close();
459         } catch (IOException e) {
460             // TODO Auto-generated catch block
461             e.printStackTrace();
462         }
463 
464         return bo;
465     }
466 
467     // 配合initFile 方法的变量
468     public static int tOneCountForInitFile = 1;
469 
470     /**
471      * 判断当前系统中是否存在该文件,如果存在则换一个名字, 也就是不会造成文件的内容覆盖。
472      * 
473      * @param filePath
474      * @return 文件名
475      */
476     public static String initFile(String filePath) {
477 
478         String tFilePath = filePath.replace("//","");
479 
480         tFilePath = tFilePath.replace("/","");
481 
482         String ss = "";
483         // 才疏学浅,真心不知道怎么处理,只能用这样的苯方法获取文件名了
484         ss = tFilePath.substring(0,tFilePath.lastIndexOf("") + 1);
485 
486         boolean bo = false;
487 
488         File[] files = new File(ss).listFiles();
489 
490         for (File file : files) {
491 
492             String str2 = file.getPath();
493 
494             if (!str2.contains("."))// 文件夹就不需要校验了
495                 continue;
496 
497             if (str2.equals(filePath)) {
498                 bo = true;
499                 break;
500             }
501         }
502 
503         if (bo) {
504 
505             if (tFilePath.contains("(")) {
506 
507                 tOneCountForInitFile++;
508                 tFilePath = filePath.substring(0,filePath.lastIndexOf("(")) + "(" + tOneCountForInitFile + ")"
509                         + filePath.substring(filePath.lastIndexOf("."),filePath.length());
510 
511             } else {
512                 tFilePath = filePath.substring(0,filePath.lastIndexOf(".")) + "(" + tOneCountForInitFile + ")"
513                         + filePath.substring(filePath.lastIndexOf("."),filePath.length());
514 
515             }
516             return initFile(tFilePath);
517         }
518         return tFilePath;
519     }
520 
521     /**
522      * @param sourceString
523      *            源字符串
524      * @param targetString
525      *            目标字符串
526      * @param count
527      *            第几次出现
528      * @param flag
529      *            查找方向(正向查找,反向查找)
530      * @return 出现的位置(都是正向开始计算)
531      * 
532      */
533 
534     public static int indexWithCount(String sourceString,String targetString,int count,int flag) {
535 
536         int lengthCount = 0;
537         if (!sourceString.contains(targetString)) // 判断是否存在目标字符串
538             return -1;
539         int strHaveHowCount = strHaveHowCount(sourceString,targetString); // 目标字符串出现了几次
540         if (strHaveHowCount < count)
541             return -1;
542         if (flag == -1) {
543             count = strHaveHowCount - count + 1;
544         } else if (flag == 1 || flag == 0) {
545             count = count;
546         } else
547             return -1;
548         int j = 0;
549         for (int i = 0; i < count; i++) {
550             if (count == 1) {
551                 lengthCount = sourceString.indexOf(targetString);
552                 return lengthCount;
553             } else {
554                 lengthCount = sourceString.indexOf(targetString,j);
555                 j = lengthCount + 1;
556             }
557         }
558         return lengthCount;
559     }
560 
561     /**
562      * @param sourceString
563      *            源字符串
564      * @param targetString
565      *            目标字符串
566      * @param count
567      *            第几次出现
568      * @return 出现的位置(都是正向开始计算) indexWithCount的方法的重构 没写最后一个参数是 默认从请往后查询
569      */
570     protected static int indexWithCount(String sourceString,int count) {
571 
572         int lengthCount = 0;
573         if (!sourceString.contains(targetString)) // 判断是否存在目标字符串
574             return -1;
575         int strHaveHowCount = strHaveHowCount(sourceString,targetString); // 目标字符串出现了几次
576         if (strHaveHowCount < count)
577             return -1;
578         int j = 0;
579         for (int i = 0; i < count; i++) {
580             if (count == 1) {
581                 lengthCount = sourceString.indexOf(targetString);
582                 return lengthCount;
583             } else {
584                 lengthCount = sourceString.indexOf(targetString,j);
585                 j = lengthCount + 1;
586             }
587         }
588         return lengthCount;
589     }
590 
591     /**
592      * 次方法就是判断出一个字符串在另一个中出出现的多少次
593      * 
594      * @param a
595      *            被匹配的长字符串
596      * @param b
597      *            匹配的短字符串
598      * @return 匹配次数
599      */
600     public static int strHaveHowCount(String sourceStr,String targetStr) {
601 
602         if (sourceStr.length() < targetStr.length()) {
603             return 0;
604         }
605         char[] a_t = sourceStr.toCharArray();
606         int count = 0;
607         for (int i = 0; i <= sourceStr.length() - targetStr.length(); i++) {// 条件必须用 <= 要不然会少比较一次
608             StringBuffer buffer = new StringBuffer();
609             for (int j = 0; j < targetStr.length(); j++) {
610                 buffer.append(a_t[i + j]);
611             }
612             if (buffer.toString().equals(targetStr)) {
613                 count++;
614             }
615         }
616         return count;
617     }
618 
619     /**
620      * 
621      * @param sourceStr
622      *            源字符串
623      * @param targetStr
624      *            目标字符串
625      * @return count 次数(注意“aaa”找“aa”这样算出现一次)
626      */
627     public static int strHaveHowCount2(String sourceStr,String targetStr) {
628 
629         int count = 0;
630 
631         if (sourceStr.length() < targetStr.length()) {
632             return count;
633         }
634 
635         int bigLength = sourceStr.length();
636         int smallLength = targetStr.length();
637 
638         String newSourceStr = "";
639 
640         if (sourceStr.contains(targetStr)) {
641             newSourceStr = sourceStr.replace(targetStr,"");
642         } else {
643             return 0;
644 
645         }
646         int newBigLength = newSourceStr.length();
647 
648         count = (bigLength - newBigLength) / smallLength;
649 
650         return count;
651     }
652 
653     /**
654      * 这个方法是读一个文本格式的文件,按行读取将内容放到一个List里面
655      * 
656      * @param filePath
657      * @return
658      */
659     public static List<String> readOneFile(String filePath) {
660         List<String> resultList = new ArrayList<String>();// 获取文件中每一行的字符串
661         int count = 0;
662         try {
663             // String encoding = "UTF-8";
664             File file = new File(filePath);
665             if (file.isFile() && file.exists()) { // 判断文件是否存在
666                 InputStreamReader read = new InputStreamReader(new FileInputStream(file));// 考虑到编码格式
667                 BufferedReader bufferedReader = new BufferedReader(read);
668                 String lineTxt = null;
669                 while ((lineTxt = bufferedReader.readLine()) != null) {
670                     resultList.add(lineTxt);
671                     // System.out.println(lineTxt);
672                     count++;
673                 }
674                 count = 0;
675                 read.close();
676             } else {
677                 System.err.println("找不到指定的文件");
678             }
679         } catch (Exception e) {
680             System.err.println("读取文件内容出错");
681             e.printStackTrace();
682         }
683         return resultList;
684     }
685 
686     /**
687      * 这个是借用了读取单个excle的方法 可以完成对一个文件夹下的所有excle内容的读取(只能读到每个excle的第一个sheet,后续完善)
688      * 
689      * @param filePaths
690      * @return
691      */
692     public List<List<String>> readExcleAll(String filePaths) {
693 
694         File[] files = new File(filePaths).listFiles();
695 
696         List<List<String>> lis = new ArrayList<List<String>>();
697 
698         for (int i = 0; i < files.length; i++) {
699 
700             List<List<String>> li = new ArrayList<List<String>>();
701 
702             li = readExcle(files[i].getPath());
703 
704             for (int j = 0; j < li.size(); j++) {
705 
706                 lis.add(li.get(j));
707             }
708         }
709 
710         System.out.println("获取多个excle后,一共得到:" + lis.size() + "====行的数据");
711         return lis;
712     }
713 
714     /**
715      * 这是为getFileList() 提供的辅助属性,用于存放所符合条件的路径
716      */
717     public List<String> oneLis = new ArrayList<String>();
718 
719     /**
720      * 获取一个文件夹下的所有文件名的绝对路径,这个方法是getFileList(String filepath)的方法的重写 可以获得 规定后缀的文件
721      * 
722      * @param filepath
723      * @return
724      */
725     public List<String> getFileList(String filepath,String engStr) {
726 
727         File file = new File(filepath);
728         File[] files = file.listFiles(); // 该文件目录下文件全部放入数组
729         if (files != null) {
730             for (int i = 0; i < files.length; i++) {
731                 String fileName = files[i].getName();
732                 if (files[i].isDirectory()) { // 判断是文件还是文件夹
733                     getFileList(files[i].getAbsolutePath(),engStr); // 获取文件绝对路径
734                 } else {
735                     if (files[i].getAbsolutePath().endsWith(engStr))
736                         oneLis.add(files[i].getAbsolutePath()); // 将符合规定后缀的文件收集到 一个集合里
737                 }
738             }
739         }
740         // 用于输出一个文件夹地址下存在多少个文件 利用了递归方法 每一条
741         // System.out.println("一同获得" + oneLis.size() + "条路径!!!!!");
742         return oneLis;
743     }
744 
745     /**
746      * 获取一个文件夹下的所有文件名的绝对路径
747      * 
748      * @param filepath
749      * @return
750      */
751     public List<String> getFileList(String filepath) {
752 
753         File file = new File(filepath);
754         File[] files = file.listFiles(); // 该文件目录下文件全部放入数组
755         if (files != null) {
756             for (int i = 0; i < files.length; i++) {
757                 String fileName = files[i].getName();
758                 if (files[i].isDirectory()) { // 判断是文件还是文件夹
759                     getFileList(files[i].getAbsolutePath()); // 获取文件绝对路径
760                 } else {
761                     oneLis.add(files[i].getAbsolutePath());
762                 }
763             }
764         }
765         System.out.println("一同获得" + oneLis.size() + "条路径!!!!!");
766         return oneLis;
767     }
768 
769     /**
770      * 
771      * 读取exce的全部sheet的数据,把每一个sheet的名称放到每一行数据的最后一列
772      * 
773      * @param cFilePath
774      * @return
775      */
776     public static List<List<String>> readExcleAllSheet(String cFilePath) {
777         List<List<String>> sumLists = new ArrayList<List<String>>();
778         ArrayList<String> sumList = null;
779         boolean isE2007 = false; // 判断是否是excel2007格式
780         if (cFilePath.endsWith(".xlsx"))
781             isE2007 = true;
782         try {
783             InputStream input = new FileInputStream(cFilePath); // 建立输入流
784             Workbook wb = null;
785             // 根据文件格式(2003或者2007)来初始化
786             if (isE2007)
787                 wb = new XSSFWorkbook(input);
788             else
789                 wb = new HSSFWorkbook(input);
790             Sheet sheet = null;// 获得第一个表单
791 
792             for (int j = 0; j < wb.getNumberOfSheets(); j++) {
793                 sheet = wb.getSheetAt(j);
794 
795                 if (sheet == null)
796                     continue;
797 
798                 Iterator<Row> rows = sheet.rowIterator(); // 获得第一个表单的迭代器
799                 while (rows.hasNext()) {
800                     Row row = rows.next(); // 获得行数据
801                     Iterator<Cell> cells = row.cellIterator(); // 获得第一行的迭代器
802                     sumList = new ArrayList<String>();
803 
804                     // 遍历一行数据装到subList中
805                     int count = 0;
806                     int countRes = 0;
807                     while (cells.hasNext()) {
808                         Cell cell = cells.next();
809                         // System.out.println(cell.getColumnIndex());
810                         count = cell.getColumnIndex();
811 
812                         int res = count - countRes;
813                         // System.out.println("应该加:"+res);
814                         if (res == 0) {
815                             sumList.add(new String(cell.toString()));
816                             countRes++;
817                         } else {
818                             for (int i = 0; i < res; i++) {
819                                 sumList.add(" ");// 空位补空格
820                                 countRes++;
821                             }
822                             sumList.add(new String(cell.toString()));
823                         }
824                     }
825                     count = 0;
826                     countRes = 0;
827                     sumList.add(sheet.getSheetName());
828                     sumLists.add(sumList);
829 
830                 }
831             }
832         } catch (IOException ex) {
833             ex.printStackTrace();
834         }
835         return sumLists;
836     }
837 
838     
839     /**
840      * 这个参数是一个set集合 为了处理那种重复数据
841      * 
842      * @param set
843      *            需要的内容
844      * @param tPath
845      *            文件绝对地址
846      * @return 虽然是boolean类型 但是没有做任何操作 后续需要在说吧
847      */
848     public static boolean writeFileAtPath(Set set,String tPath) {
849 
850         Excle ex = new Excle();
851         Iterator iterator = set.iterator();
852         String endPath = ex.initFile(tPath);// 将生成的sql放到指点的文件地址
853         File file = new File(endPath);
854         FileWriter fw = null;
855         BufferedWriter writer = null;
856         try {
857             fw = new FileWriter(file);
858             writer = new BufferedWriter(fw);
859             while (iterator.hasNext()) {
860                 writer.write(iterator.next().toString());
861                 writer.newLine();// 换行
862             }
863             writer.flush();
864         } catch (FileNotFoundException e) {
865             e.printStackTrace();
866         } catch (IOException e) {
867             e.printStackTrace();
868         } finally {
869             try {
870                 writer.close();
871                 fw.close();
872             } catch (IOException e) {
873                 e.printStackTrace();
874             }
875         }
876         return true;
877     }
878 
879     /**
880      * 这个参数是一个list集合 可以做到有序
881      * 
882      * @param list
883      *            需要的内容
884      * @param tPath
885      *            文件的绝对地址
886      * @return 虽然是boolean类型 但是没有做任何操作 后续需要在说吧
887      */
888     public static boolean writeFileAtPath(List list,String tPath) {
889 
890         Excle ex = new Excle();
891         Iterator iterator = list.iterator();
892         String endPath = ex.initFile(tPath);// 将生成的sql放到指点的文件地址
893         File file = new File(endPath);
894         FileWriter fw = null;
895         BufferedWriter writer = null;
896         try {
897             fw = new FileWriter(file);
898             writer = new BufferedWriter(fw);
899             while (iterator.hasNext()) {
900                 writer.write(iterator.next().toString());
901                 writer.newLine();// 换行
902             }
903             writer.flush();
904         } catch (FileNotFoundException e) {
905             e.printStackTrace();
906         } catch (IOException e) {
907             e.printStackTrace();
908         } finally {
909             try {
910                 writer.close();
911                 fw.close();
912             } catch (IOException e) {
913                 e.printStackTrace();
914             }
915         }
916         return false;
917     }
918 
919     public static void main(String[] args) throws IOException {
920 
921         //initFile("E:nety");
922 
923     }
924 
925 }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读