zoukankan      html  css  js  c++  java
  • java使用poi包将数据写入Excel表格

    1、Excel相关操作代码

      1 import java.io.File;
      2 import java.io.FileInputStream;
      3 import java.io.FileNotFoundException;
      4 import java.io.FileOutputStream;
      5 import java.io.IOException;
      6 import java.lang.reflect.Field;
      7 import java.lang.reflect.Method;
      8 import java.util.ArrayList;
      9 import java.util.List;
     10 
     11 import org.apache.poi.hssf.usermodel.HSSFRow;
     12 import org.apache.poi.hssf.usermodel.HSSFSheet;
     13 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     14 import org.apache.poi.ss.usermodel.Cell;
     15 import org.apache.poi.ss.usermodel.Row;
     16 import org.springframework.stereotype.Component;
     17 
     18 /**
     19  * @Description: 
     20  * @author 21  * @date 创建时间:2016年12月8日下午2:38:47
     22  * @version 1.0
     23  */
     24 @Component
     25 public class ExcelManage {
     26     private HSSFWorkbook workbook = null;  
     27     
     28     /** 
     29      * 判断文件是否存在
     30      * @param filePath  文件路径 
     31      * @return 
     32      */  
     33     public boolean fileExist(String filePath){  
     34          boolean flag = false;  
     35          File file = new File(filePath);  
     36          flag = file.exists();  
     37          return flag;  
     38     }  
     39     
     40     /** 
     41      * 判断文件的sheet是否存在
     42      * @param filePath   文件路径 
     43      * @param sheetName  表格索引名 
     44      * @return 
     45      */  
     46     public boolean sheetExist(String filePath,String sheetName){  
     47          boolean flag = false;  
     48          File file = new File(filePath);  
     49          if(file.exists()){    //文件存在  
     50             //创建workbook  
     51              try {  
     52                 workbook = new HSSFWorkbook(new FileInputStream(file));  
     53                 //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)  
     54                 HSSFSheet sheet = workbook.getSheet(sheetName);    
     55                 if(sheet!=null)  
     56                     flag = true;  
     57             } catch (Exception e) {  
     58                 e.printStackTrace();  
     59             }                 
     60          }else{    //文件不存在  
     61              flag = false;  
     62          }            
     63          return flag;  
     64     }
     65     /** 
     66      * 创建新Sheet并写入第一行数据
     67      * @param filePath  excel的路径 
     68      * @param sheetName 要创建的表格索引 
     69      * @param titleRow excel的第一行即表格头 
     70      * @throws IOException 
     71      * @throws FileNotFoundException 
     72      */  
     73     public void createSheet(String filePath,String sheetName,String titleRow[]) throws FileNotFoundException, IOException{ 
     74         FileOutputStream out = null;         
     75         File excel = new File(filePath);  // 读取文件
     76         FileInputStream in = new FileInputStream(excel); // 转换为流
     77         workbook = new HSSFWorkbook(in); // 加载excel的 工作目录       
     78                           
     79         workbook.createSheet(sheetName); // 添加一个新的sheet  
     80         //添加表头  
     81         Row row = workbook.getSheet(sheetName).createRow(0);    //创建第一行            
     82         try {              
     83             for(int i = 0;i < titleRow.length;i++){  
     84                 Cell cell = row.createCell(i);  
     85                 cell.setCellValue(titleRow[i]);  
     86             } 
     87             out = new FileOutputStream(filePath);  
     88             workbook.write(out);
     89        }catch (Exception e) {  
     90            e.printStackTrace();  
     91        }finally {    
     92            try {    
     93                out.close();    
     94            } catch (IOException e) {    
     95                e.printStackTrace();  
     96            }    
     97        }             
     98     }
     99     /** 
    100      * 创建新excel. 
    101      * @param filePath  excel的路径 
    102      * @param sheetName 要创建的表格索引 
    103      * @param titleRow excel的第一行即表格头 
    104      */  
    105     public void createExcel(String filePath,String sheetName,String titleRow[]){  
    106         //创建workbook  
    107         workbook = new HSSFWorkbook();  
    108         //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)  
    109         workbook.createSheet(sheetName);    
    110         //新建文件  
    111         FileOutputStream out = null;  
    112         try {  
    113             //添加表头  
    114             Row row = workbook.getSheet(sheetName).createRow(0);    //创建第一行    
    115             for(int i = 0;i < titleRow.length;i++){  
    116                 Cell cell = row.createCell(i);  
    117                 cell.setCellValue(titleRow[i]);  
    118             }               
    119             out = new FileOutputStream(filePath);  
    120             workbook.write(out);  
    121         } catch (Exception e) {  
    122             e.printStackTrace();  
    123         } finally {    
    124             try {    
    125                 out.close();    
    126             } catch (IOException e) {    
    127                 e.printStackTrace();  
    128             }    
    129         }    
    130     }  
    131     /** 
    132      * 删除文件. 
    133      * @param filePath  文件路径 
    134      */  
    135     public boolean deleteExcel(String filePath){  
    136         boolean flag = false;  
    137         File file = new File(filePath);  
    138         // 判断目录或文件是否存在    
    139         if (!file.exists()) {  
    140             return flag;    
    141         } else {    
    142             // 判断是否为文件    
    143             if (file.isFile()) {  // 为文件时调用删除文件方法    
    144                 file.delete();  
    145                 flag = true;  
    146             }   
    147         }  
    148         return flag;  
    149     }  
    150     /** 
    151      * 往excel中写入. 
    152      * @param filePath    文件路径 
    153      * @param sheetName  表格索引 
    154      * @param object 
    155      */  
    156     public void writeToExcel(String filePath,String sheetName, Object object,String titleRow[]){  
    157         //创建workbook  
    158         File file = new File(filePath);  
    159         try {  
    160             workbook = new HSSFWorkbook(new FileInputStream(file));  
    161         } catch (FileNotFoundException e) {  
    162             e.printStackTrace();  
    163         } catch (IOException e) {  
    164             e.printStackTrace();  
    165         }  
    166         FileOutputStream out = null;  
    167         HSSFSheet sheet = workbook.getSheet(sheetName);  
    168         // 获取表格的总行数  
    169         int rowCount = sheet.getLastRowNum() + 1; // 需要加一  
    170         try {  
    171             Row row = sheet.createRow(rowCount);     //最新要添加的一行  
    172             //通过反射获得object的字段,对应表头插入  
    173             // 获取该对象的class对象  
    174             Class<? extends Object> class_ = object.getClass();              
    175             
    176             for(int i = 0;i < titleRow.length;i++){    
    177                 String title = titleRow[i];
    178                 String UTitle = Character.toUpperCase(title.charAt(0))+ title.substring(1, title.length()); // 使其首字母大写;  
    179                 String methodName  = "get"+UTitle;  
    180                 Method method = class_.getDeclaredMethod(methodName); // 设置要执行的方法  
    181                 String data = method.invoke(object).toString(); // 执行该get方法,即要插入的数据  
    182                 Cell cell = row.createCell(i);  
    183                 cell.setCellValue(data);  
    184             }           
    185             out = new FileOutputStream(filePath);  
    186             workbook.write(out);  
    187         } catch (Exception e) {  
    188             e.printStackTrace();  
    189         } finally {    
    190             try {    
    191                 out.close();    
    192             } catch (IOException e) {    
    193                 e.printStackTrace();  
    194             }    
    195         }    
    196     }  
    197 }

    2、main方法调用方式

     1 public static void main(String[] args) {  
     2     String filePath = "result/数据汇总.xls";
     3     String sheetName = "测试";
     4     //Excel文件易车sheet页的第一行 
     5     String title[] = {"日期", "城市","新发布车源数"};
     6     //Excel文件易车每一列对应的数据
     7     String titleDate[] = {"date", "city","newPublish"};
     8         
     9     ExcelManage em = new ExcelManage();  
    10     //判断该名称的文件是否存在  
    11     boolean fileFlag = em.fileExist(filePath);        
    12     if(!fileFlag){
    13        em.createExcel(filePath,sheetName,title);
    14     }  
    15     //判断该名称的Sheet是否存在  
    16     boolean sheetFlag = em.sheetExist(filePath,sheetName);
    17     //如果该名称的Sheet不存在,则新建一个新的Sheet
    18     if(!sheetFlag){
    19        try {
    20            em.createSheet(filePath,sheetName,title);
    21        } catch (FileNotFoundException e) {
    22            e.printStackTrace();
    23        } catch (IOException e) {
    24            e.printStackTrace();
    25        }
    26     }          
    28     YiCheData user = new YiCheData();  
    29     user.setDate("206-12-21");  
    30     user.setCity("北京");  
    31     user.setNewPublish("5");  
    32     //写入到excel 
    33     em.writeToExcel(filePath,sheetName,user,titleDate);  
    34 }

    3、用于测试的bean类

     1 public class YiCheData {
     2     private String date;  
     3     private String city;  
     4     private String newPublish;  
     5    
     6     public String getDate() {
     7         return date;
     8     }
     9     public void setDate(String date) {
    10         this.date = date;
    11     }
    12     public String getCity() {
    13       return city;
    14     }
    15     public void setCity(String city) {
    16       this.city = city;
    17     }
    18     public String getNewPublish() {
    19       eturn newPublish;
    20     }
    21     public void setNewPublish(String newPublish) {
    22       this.newPublish = newPublish;
    23     }
    24 }        

     以上代码请参考:http://www.open-open.com/lib/view/open1433238476150.html

  • 相关阅读:
    第6章 函数 习题
    2. VS使用---HelloWorld
    [计蒜客]小 B 的题目
    [计蒜客] n 子棋
    [博弈]Euclid's Game
    [博弈]A Funny Game
    [博弈]Being a Good Boy in Spring Festival
    [组合数学]Magic 12 Months(坑)
    [PTA]L2-031 深入虎穴 (25 分)
    [天梯赛]L2-029 特立独行的幸福
  • 原文地址:https://www.cnblogs.com/dingziyin/p/6208749.html
Copyright © 2011-2022 走看看