Java处理excel文件

好久好久没写blog了,感觉都生锈了,最近弄了弄java处理excel,特来简单粘贴一下:

  1 package excel;
  2 
  3 import java.io.BufferedInputStream;
  4 import java.io.File;
  5 import java.io.FileInputStream;
  6 import java.io.FileOutputStream;
  7 import java.text.SimpleDateFormat;
  8 import java.util.ArrayList;
  9 import java.util.Date;
 10 import java.util.List;
 11 import java.util.Scanner;
 12 
 13 import javax.swing.JFrame;
 14 
 15 import org.apache.poi.hssf.usermodel.HSSFCell;
 16 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 17 import org.apache.poi.hssf.usermodel.HSSFRow;
 18 import org.apache.poi.hssf.usermodel.HSSFSheet;
 19 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 20 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 21 import org.apache.poi.ss.usermodel.Cell;
 22 import org.apache.poi.ss.usermodel.CellStyle;
 23 import org.apache.poi.ss.usermodel.Row;
 24 import org.apache.poi.ss.usermodel.Sheet;
 25 import org.apache.poi.ss.usermodel.Workbook;
 26 import org.apache.poi.ss.util.Region;
 27 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 28 
 29 import excel.MedicineBean;
 30 
 31 
 32 public class ExcelHandler {
 33     
 34     private String errorInfo; 
 35     private List<MedicineBean> list = new ArrayList<MedicineBean>();
 36     
 37     /**
 38      * 判断文件是否存在
 39      * @param filePath
 40      * @return
 41      */
 42     public boolean validateExcel(String filePath)  
 43     {  
 44   
 45         /** 检查文件名是否为空或者是否是Excel格式的文件 */  
 46   
 47         if (filePath == null || !(WDWUtil.isExcel2003(filePath) || WDWUtil.isExcel2007(filePath)))  
 48         {  
 49   
 50             errorInfo = "文件名不是excel格式"; 
 51             System.out.println(errorInfo);
 52   
 53             return false;  
 54   
 55         }  
 56   
 57         /** 检查文件是否存在 */  
 58   
 59         File file = new File(filePath);  
 60   
 61         if (file == null || !file.exists())  
 62         {  
 63   
 64             errorInfo = "文件不存在"; 
 65             System.out.println(errorInfo);
 66   
 67             return false;  
 68   
 69         }  
 70   
 71         return true;  
 72   
 73     } 
 74     
 75     /**
 76      * 从Excel中读取数据到内存
 77      * @param filePath
 78      * @return
 79      */
 80     public List<MedicineBean> readExcelData(String filePath){
 81         list = new ArrayList<MedicineBean>();
 82         FileInputStream fis=null;
 83         if(!validateExcel(filePath))//检测文件是否合法
 84             return null;
 85         try {
 86             fis=new FileInputStream(filePath);
 87             Workbook workbook=null;
 88             if (WDWUtil.isExcel2003(filePath))  
 89             {      POIFSFileSystem fs=new POIFSFileSystem(fis);
 90                 workbook = new HSSFWorkbook(fs);  
 91             }  
 92             else  
 93             {  
 94                 workbook = new XSSFWorkbook(new BufferedInputStream(fis));  
 95                 
 96             }  
 97             Sheet sheet =workbook.getSheetAt(3);
 98             for(int i=2;i<=sheet.getLastRowNum();i++){
 99                 MedicineBean bean = new MedicineBean();
100                 Row row=sheet.getRow(i);
101                 Cell cell1=row.getCell(0);
102                 Cell cell2=row.getCell(1);
103                 Cell cell3=row.getCell(2);
104                 Cell cell4=row.getCell(3);
105                 Cell cell5=row.getCell(4);
106                 Cell cell6=row.getCell(5);
107                 Cell cell7=row.getCell(6);
108                 Cell cell8=row.getCell(7);
109                 Cell cell9=row.getCell(8);
110                 Cell cell10=row.getCell(9);
111                 Cell cell11=row.getCell(10);
112                 SimpleDateFormat sdf = null;
113                 sdf = new SimpleDateFormat("yyyy/MM/dd");
114                 Date date = cell11.getDateCellValue();
115                 bean.setId(String.valueOf(Math.round(cell1.getNumericCellValue())));
116                 bean.setNumber(cell2.getStringCellValue());
117                 bean.setCode(String.valueOf(Math.round(cell3.getNumericCellValue())));
118                 bean.setRegisterName(cell4.getStringCellValue());
119                 bean.setEnglishName(cell5.getStringCellValue());
120                 bean.setType(cell6.getStringCellValue());
121                 bean.setFormat(cell7.getStringCellValue());
122                 bean.setManufacturer(cell8.getStringCellValue());
123                 bean.setAuthorizeNumber(cell9.getStringCellValue());
124                 bean.setRemark(cell10.getStringCellValue());
125                 bean.setDate(sdf.format(date));
126                 //System.out.println(bean.getId()+"  "+bean.getDate()+" "+ bean.getCode()+" "+bean.getRegisterName());
127                 list.add(bean);
128             }
129             fis.close();
130             return list;
131             
132         } catch (Exception e) {
133             e.printStackTrace();
134             return null;
135         }
136     }
137     
138     /**
139      * 数据导出到Excel表,可用于数据备份
140      * @param list
141      * @return
142      */
143     public boolean readDataToExcelFile(List<MedicineBean> list){
144         try{
145             HSSFWorkbook workbook;
146             HSSFSheet sheet;
147             HSSFCellStyle cellstyle;
148             if (validateExcel("C:\Users\george\Desktop\export.xls")){
149                 FileInputStream fs=new FileInputStream("C:\Users\george\Desktop\export.xls");  //获取d://test.xls  
150                 POIFSFileSystem ps=new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息  
151                 workbook=new HSSFWorkbook(ps);   
152                 cellstyle=workbook.createCellStyle();
153                 sheet= workbook.getSheetAt(0);  //获取到工作表,因为一个excel可能有多个工作表
154             } else {
155                 HSSFRow row1;
156                 workbook = new HSSFWorkbook();
157                 sheet=workbook.createSheet();
158                 workbook.setSheetName(0, "test");
159                 row1 = sheet.createRow(0);
160                 sheet.addMergedRegion(new Region(0,(short)0,0,(short)10));
161                 cellstyle=workbook.createCellStyle();
162                 HSSFCell tittleCell=row1.createCell(0);
163                 tittleCell.setCellValue("西药药品关联信息参考数据库");
164                 tittleCell.setCellStyle(cellstyle);
165             }
166             cellstyle.setAlignment(CellStyle.ALIGN_CENTER);
167             cellstyle.setVerticalAlignment(CellStyle.ALIGN_CENTER);
168             int lastNum = sheet.getLastRowNum();
169             HSSFRow dataRow=sheet.createRow(lastNum+1);//创建行    
170             lastNum++;
171             HSSFCell staffcell=dataRow.createCell(0);//创建单元格
172             staffcell.setCellValue("ID");//设置单元格中的数据
173             staffcell.setCellStyle(cellstyle);//设置单元格内容居中
174             
175             HSSFCell orgcell=dataRow.createCell(1);//创建单元格
176             orgcell.setCellValue("西药药品代码");//设置单元格中的数据
177             orgcell.setCellStyle(cellstyle);//设置单元格内容居中
178             
179             HSSFCell syscell=dataRow.createCell(2);//创建单元格
180             syscell.setCellValue("药监局药品编码");//设置单元格中的数据
181             syscell.setCellStyle(cellstyle);//设置单元格内容居中
182             
183             HSSFCell menucell=dataRow.createCell(3);//创建单元格
184             menucell.setCellValue("药品注册名称");//设置单元格中的数据
185             menucell.setCellStyle(cellstyle);//设置单元格内容居中
186             
187             HSSFCell limitcell=dataRow.createCell(4);//创建单元格
188             limitcell.setCellValue("英文名称");//设置单元格中的数据
189             limitcell.setCellStyle(cellstyle);//设置单元格内容居中
190             
191             HSSFCell scopecell=dataRow.createCell(5);//创建单元格
192             scopecell.setCellValue("药品注册剂型");//设置单元格中的数据
193             scopecell.setCellStyle(cellstyle);//设置单元格内容居中
194             
195             HSSFCell standby1cell=dataRow.createCell(6);//创建单元格
196             standby1cell.setCellValue("药品注册规格");//设置单元格中的数据
197             standby1cell.setCellStyle(cellstyle);//设置单元格内容居中
198             
199             HSSFCell standby2cell=dataRow.createCell(7);//创建单元格
200             standby2cell.setCellValue("生产单位");//设置单元格中的数据
201             standby2cell.setCellStyle(cellstyle);//设置单元格内容居中
202             
203             HSSFCell standby3cell=dataRow.createCell(8);//创建单元格
204             standby3cell.setCellValue("批准文号");//设置单元格中的数据
205             standby3cell.setCellStyle(cellstyle);//设置单元格内容居中
206             
207             HSSFCell standby4cell=dataRow.createCell(9);//创建单元格
208             standby4cell.setCellValue("批准文号备注");//设置单元格中的数据
209             standby4cell.setCellStyle(cellstyle);//设置单元格内容居中
210             
211             HSSFCell standby5cell=dataRow.createCell(10);//创建单元格
212             standby5cell.setCellValue("批准日期");//设置单元格中的数据
213             standby5cell.setCellStyle(cellstyle);//设置单元格内容居中
214             for(int i=0;i<list.size();i++){
215                 MedicineBean model=list.get(i);
216                 dataRow=sheet.createRow(lastNum+1);//创建行    
217                 lastNum++;
218                 staffcell=dataRow.createCell(0);//创建单元格
219                 staffcell.setCellValue(model.getId());//设置单元格中的数据
220                 staffcell.setCellStyle(cellstyle);//设置单元格内容居中
221                 
222                 orgcell=dataRow.createCell(1);//创建单元格
223                 orgcell.setCellValue(model.getNumber());//设置单元格中的数据
224                 orgcell.setCellStyle(cellstyle);//设置单元格内容居中
225                 
226                 syscell=dataRow.createCell(2);//创建单元格
227                 syscell.setCellValue(model.getCode());//设置单元格中的数据
228                 syscell.setCellStyle(cellstyle);//设置单元格内容居中
229                 
230                 menucell=dataRow.createCell(3);//创建单元格
231                 menucell.setCellValue(model.getRegisterName());//设置单元格中的数据
232                 menucell.setCellStyle(cellstyle);//设置单元格内容居中
233                 
234                 limitcell=dataRow.createCell(4);//创建单元格
235                 limitcell.setCellValue(model.getEnglishName());//设置单元格中的数据
236                 limitcell.setCellStyle(cellstyle);//设置单元格内容居中
237                 
238                 scopecell=dataRow.createCell(5);//创建单元格
239                 scopecell.setCellValue(model.getType());//设置单元格中的数据
240                 scopecell.setCellStyle(cellstyle);//设置单元格内容居中
241                 
242                 standby1cell=dataRow.createCell(6);//创建单元格
243                 standby1cell.setCellValue(model.getFormat());//设置单元格中的数据
244                 standby1cell.setCellStyle(cellstyle);//设置单元格内容居中
245                 
246                 standby2cell=dataRow.createCell(7);//创建单元格
247                 standby2cell.setCellValue(model.getManufacturer());//设置单元格中的数据
248                 standby2cell.setCellStyle(cellstyle);//设置单元格内容居中
249                 
250                 standby3cell=dataRow.createCell(8);//创建单元格
251                 standby3cell.setCellValue(model.getAuthorizeNumber());//设置单元格中的数据
252                 standby3cell.setCellStyle(cellstyle);//设置单元格内容居中
253                 
254                 standby4cell=dataRow.createCell(9);//创建单元格
255                 standby4cell.setCellValue(model.getRemark());//设置单元格中的数据
256                 standby4cell.setCellStyle(cellstyle);//设置单元格内容居中
257                 
258                 standby5cell=dataRow.createCell(10);//创建单元格
259                 standby5cell.setCellValue(model.getDate());//设置单元格中的数据
260                 standby5cell.setCellStyle(cellstyle);//设置单元格内容居中
261             }
262             File xlsFile=new File("C:\Users\george\Desktop\export.xls");
263             FileOutputStream fos=new FileOutputStream(xlsFile);    
264             workbook.write(fos);
265             fos.close();
266             return true;
267             
268             
269         }catch(Exception e){
270             e.printStackTrace();
271             return false;
272         }
273         
274     }
275     
276     /**
277      * 将数据修改并添加到edited。xls文件里
278      * @param bean
279      * @return
280      */
281     public boolean editExcelById(MedicineBean bean){
282         try{
283             HSSFWorkbook workbook;
284             HSSFSheet sheet;
285             HSSFCellStyle cellstyle;
286             if (validateExcel("C:\Users\george\Desktop\edited.xls")){
287                 FileInputStream fs=new FileInputStream("C:\Users\george\Desktop\edited.xls");   
288                 POIFSFileSystem ps=new POIFSFileSystem(fs);  //使用POI提供的方法得到excel的信息  
289                 workbook=new HSSFWorkbook(ps);   
290                 cellstyle=workbook.createCellStyle();
291                 sheet= workbook.getSheetAt(0);  //获取到工作表,因为一个excel可能有多个工作表
292             } else {
293                 HSSFRow row1;
294                 workbook = new HSSFWorkbook();
295                 sheet=workbook.createSheet();
296                 workbook.setSheetName(0, "test");
297                 row1 = sheet.createRow(0);
298                 sheet.addMergedRegion(new Region(0,(short)0,0,(short)10));
299                 cellstyle=workbook.createCellStyle();
300                 HSSFCell tittleCell=row1.createCell(0);
301                 tittleCell.setCellValue("西药药品关联信息参考数据库");
302                 tittleCell.setCellStyle(cellstyle);
303             }
304             cellstyle.setAlignment(CellStyle.ALIGN_CENTER);
305             cellstyle.setVerticalAlignment(CellStyle.ALIGN_CENTER);
306             int lastNum = sheet.getLastRowNum();
307             HSSFRow dataRow;
308             HSSFCell staffcell,orgcell,syscell,menucell,limitcell,scopecell,standby1cell;
309             HSSFCell standby2cell,standby3cell,standby4cell,standby5cell;
310             if (!validateExcel("C:\Users\george\Desktop\edited.xls")){
311                 dataRow=sheet.createRow(lastNum+1);//创建行    
312                 lastNum++;
313                 staffcell=dataRow.createCell(0);//创建单元格
314                 staffcell.setCellValue("ID");//设置单元格中的数据
315                 staffcell.setCellStyle(cellstyle);//设置单元格内容居中
316                 
317                 orgcell=dataRow.createCell(1);//创建单元格
318                 orgcell.setCellValue("西药药品代码");//设置单元格中的数据
319                 orgcell.setCellStyle(cellstyle);//设置单元格内容居中
320                 
321                 syscell=dataRow.createCell(2);//创建单元格
322                 syscell.setCellValue("药监局药品编码");//设置单元格中的数据
323                 syscell.setCellStyle(cellstyle);//设置单元格内容居中
324                 
325                 menucell=dataRow.createCell(3);//创建单元格
326                 menucell.setCellValue("药品注册名称");//设置单元格中的数据
327                 menucell.setCellStyle(cellstyle);//设置单元格内容居中
328                 
329                 limitcell=dataRow.createCell(4);//创建单元格
330                 limitcell.setCellValue("英文名称");//设置单元格中的数据
331                 limitcell.setCellStyle(cellstyle);//设置单元格内容居中
332                 
333                 scopecell=dataRow.createCell(5);//创建单元格
334                 scopecell.setCellValue("药品注册剂型");//设置单元格中的数据
335                 scopecell.setCellStyle(cellstyle);//设置单元格内容居中
336                 
337                 standby1cell=dataRow.createCell(6);//创建单元格
338                 standby1cell.setCellValue("药品注册规格");//设置单元格中的数据
339                 standby1cell.setCellStyle(cellstyle);//设置单元格内容居中
340                 
341                 standby2cell=dataRow.createCell(7);//创建单元格
342                 standby2cell.setCellValue("生产单位");//设置单元格中的数据
343                 standby2cell.setCellStyle(cellstyle);//设置单元格内容居中
344                 
345                 standby3cell=dataRow.createCell(8);//创建单元格
346                 standby3cell.setCellValue("批准文号");//设置单元格中的数据
347                 standby3cell.setCellStyle(cellstyle);//设置单元格内容居中
348                 
349                 standby4cell=dataRow.createCell(9);//创建单元格
350                 standby4cell.setCellValue("批准文号备注");//设置单元格中的数据
351                 standby4cell.setCellStyle(cellstyle);//设置单元格内容居中
352                 
353                 standby5cell=dataRow.createCell(10);//创建单元格
354                 standby5cell.setCellValue("批准日期");//设置单元格中的数据
355                 standby5cell.setCellStyle(cellstyle);//设置单元格内容居中
356             }
357             MedicineBean model=bean;
358             dataRow=sheet.createRow(lastNum+1);//创建行    
359             lastNum++;
360             staffcell=dataRow.createCell(0);//创建单元格
361             staffcell.setCellValue(model.getId());//设置单元格中的数据
362             staffcell.setCellStyle(cellstyle);//设置单元格内容居中
363             
364             orgcell=dataRow.createCell(1);//创建单元格
365             orgcell.setCellValue(model.getNumber());//设置单元格中的数据
366             orgcell.setCellStyle(cellstyle);//设置单元格内容居中
367             
368             syscell=dataRow.createCell(2);//创建单元格
369             syscell.setCellValue(model.getCode());//设置单元格中的数据
370             syscell.setCellStyle(cellstyle);//设置单元格内容居中
371             
372             menucell=dataRow.createCell(3);//创建单元格
373             menucell.setCellValue(model.getRegisterName());//设置单元格中的数据
374             menucell.setCellStyle(cellstyle);//设置单元格内容居中
375             
376             limitcell=dataRow.createCell(4);//创建单元格
377             limitcell.setCellValue(model.getEnglishName());//设置单元格中的数据
378             limitcell.setCellStyle(cellstyle);//设置单元格内容居中
379             
380             scopecell=dataRow.createCell(5);//创建单元格
381             scopecell.setCellValue(model.getType());//设置单元格中的数据
382             scopecell.setCellStyle(cellstyle);//设置单元格内容居中
383             
384             standby1cell=dataRow.createCell(6);//创建单元格
385             standby1cell.setCellValue(model.getFormat());//设置单元格中的数据
386             standby1cell.setCellStyle(cellstyle);//设置单元格内容居中
387             
388             standby2cell=dataRow.createCell(7);//创建单元格
389             standby2cell.setCellValue(model.getManufacturer());//设置单元格中的数据
390             standby2cell.setCellStyle(cellstyle);//设置单元格内容居中
391             
392             standby3cell=dataRow.createCell(8);//创建单元格
393             standby3cell.setCellValue(model.getAuthorizeNumber());//设置单元格中的数据
394             standby3cell.setCellStyle(cellstyle);//设置单元格内容居中
395             
396             standby4cell=dataRow.createCell(9);//创建单元格
397             standby4cell.setCellValue(model.getRemark());//设置单元格中的数据
398             standby4cell.setCellStyle(cellstyle);//设置单元格内容居中
399             
400             standby5cell=dataRow.createCell(10);//创建单元格
401             standby5cell.setCellValue(model.getDate());//设置单元格中的数据
402             standby5cell.setCellStyle(cellstyle);//设置单元格内容居中
403             File xlsFile=new File("C:\Users\george\Desktop\edited.xls");
404             FileOutputStream fos=new FileOutputStream(xlsFile);    
405             workbook.write(fos);
406             fos.close();
407             return true;
408             
409             
410         }catch(Exception e){
411             e.printStackTrace();
412             return false;
413         }
414     }
415     
416     /**
417      * 从键盘输入信息修改,每次一个
418      */
419     public void inputMedicine(){
420         Scanner input =new Scanner(System.in);
421         System.out.println("输入需要更改的药品Id:");
422         int id = input.nextInt();
423         MedicineBean show = list.get(id-1);
424         System.out.println(show.getId() + "  " + show.getRegisterName() + "  " + show.getEnglishName() + "  " + show.getDate());
425         System.out.println("输入需要更改药品信息:");
426         String fl = input.nextLine();
427         System.out.println("输入西药药品代码:");
428         String number = input.nextLine();
429         System.out.println("输入药监局药品编码:");
430         String code = input.nextLine();
431         System.out.println("输入西药药品注册名称:");
432         String register = input.nextLine();
433         System.out.println("输入药品英文名称:");
434         String eng = input.nextLine();
435         System.out.println("输入药品注册剂型:");
436         String type = input.nextLine();
437         System.out.println("输入药品注册规格:");
438         String format = input.nextLine();
439         System.out.println("输入药品生产单位:");
440         String man = input.nextLine();
441         System.out.println("输入批准文号:");
442         String auth = input.nextLine();
443         System.out.println("输入批准文号备注:");
444         String remark = input.nextLine();
445         System.out.println("输入批准日期:");
446         String date = input.nextLine();
447         MedicineBean edit = new MedicineBean();
448         edit.setId(show.getId());
449         edit.setNumber(number);
450         edit.setCode(code);
451         edit.setRegisterName(register);
452         edit.setEnglishName(eng);
453         edit.setType(type);
454         edit.setFormat(format);
455         edit.setManufacturer(man);
456         edit.setAuthorizeNumber(auth);
457         edit.setRemark(remark);
458         edit.setDate(date);
459         input.close();
460         editExcelById(edit);
461         System.out.println("更改单独内容已经输出到:edited。xls文件,请查看!");
462         
463     }
464     
465     /**
466      * 主函数用于测试
467      * @param args
468      */
469     public static void main(String[] args){
470         String filePath = "C:\Users\george\Desktop\test1.xlsx";
471         ExcelHandler handler = new ExcelHandler();
472         List<MedicineBean> list = new ArrayList<MedicineBean>();
473         list = handler.readExcelData(filePath);
474         handler.readDataToExcelFile(list);
475         handler.inputMedicine();
476     }
477     
478 }
479 
480 
481 
482 class WDWUtil  
483 {  
484   
485     /** 
486      *  
487      * @描述:是否是2003的excel,返回true是2003 
488      *  
489      * @参数:@param filePath 文件完整路径 
490      *  
491      * @参数:@return 
492      *  
493      * @返回值:boolean 
494      */  
495   
496     public static boolean isExcel2003(String filePath)  
497     {  
498   
499         return filePath.matches("^.+\.(?i)(xls)$");  
500   
501     }  
502   
503     /** 
504      *  
505      * @描述:是否是2007的excel,返回true是2007 
506      *  
507      * @参数:@param filePath 文件完整路径 
508      *  
509      * @参数:@return 
510      *  
511      * @返回值:boolean 
512      */  
513   
514     public static boolean isExcel2007(String filePath)  
515     {  
516   
517         return filePath.matches("^.+\.(?i)(xlsx)$");  
518   
519     }  
520   
521 }  

原文地址:https://www.cnblogs.com/george-cw/p/4484899.html