zoukankan      html  css  js  c++  java
  • POI操作Excel详解,HSSF和XSSF两种方式

    HSSF方式:

      1 package com.tools.poi.lesson1;
      2 
      3 import java.io.FileInputStream;
      4 import java.io.FileNotFoundException;
      5 import java.io.FileOutputStream;
      6 import java.io.IOException;
      7 import java.text.ParseException;
      8 import java.text.SimpleDateFormat;
      9 import java.util.ArrayList;
     10 import java.util.List;
     11 
     12 import org.apache.poi.hssf.usermodel.HSSFCell;
     13 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
     14 import org.apache.poi.hssf.usermodel.HSSFRow;
     15 import org.apache.poi.hssf.usermodel.HSSFSheet;
     16 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     17 import org.apache.poi.hssf.util.HSSFColor;
     18 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
     19 import org.apache.poi.ss.usermodel.Cell;
     20 import org.apache.poi.ss.usermodel.CellStyle;
     21 
     22 import com.tools.poi.bean.Student;
     23 
     24 public class ExcelUtilWithHSSF {
     25     public static void main(String[] args) {
     26         try {
     27             getExcelAsFile("aaa");
     28         } catch (FileNotFoundException e) {
     29             e.printStackTrace();
     30         } catch (IOException e) {
     31             e.printStackTrace();
     32         }
     33         
     34         
     35 //        try {
     36 //            CreateExcelDemo1();
     37 //        } catch (ParseException e) {
     38 //            e.printStackTrace();
     39 //        }
     40         
     41         
     42     }
     43     
     44     /**
     45      * 得到Excel,并解析内容
     46      * @param file
     47      * @throws FileNotFoundException
     48      * @throws IOException
     49      */
     50     public static void getExcelAsFile(String file) throws FileNotFoundException, IOException{
     51         //1.得到Excel常用对象
     52 //        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/test.xls"));
     53         POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));
     54         //2.得到Excel工作簿对象
     55         HSSFWorkbook wb = new HSSFWorkbook(fs);
     56         //3.得到Excel工作表对象
     57         HSSFSheet sheet = wb.getSheetAt(0);
     58         //总行数
     59         int trLength = sheet.getLastRowNum();
     60         //4.得到Excel工作表的行
     61         HSSFRow row = sheet.getRow(0);
     62         //总列数
     63         int tdLength = row.getLastCellNum();
     64         //5.得到Excel工作表指定行的单元格
     65         HSSFCell cell = row.getCell((short)1);
     66         //6.得到单元格样式
     67         CellStyle cellStyle = cell.getCellStyle();
     68         for(int i=0;i<trLength;i++){
     69             //得到Excel工作表的行
     70             HSSFRow row1 = sheet.getRow(i);
     71             for(int j=0;j<tdLength;j++){
     72                 
     73             //得到Excel工作表指定行的单元格
     74             HSSFCell cell1 = row1.getCell(j);
     75             
     76             /**
     77              * 为了处理:Excel异常Cannot get a text value from a numeric cell
     78              * 将所有列中的内容都设置成String类型格式
     79              */
     80             if(cell1!=null){
     81                   cell1.setCellType(Cell.CELL_TYPE_STRING);
     82              }
     83             
     84             //获得每一列中的值
     85             System.out.print(cell1.getStringCellValue()+"			");
     86             }
     87             System.out.println();
     88         }
     89     }
     90     
     91     
     92     /**
     93      * 创建Excel,并写入内容
     94      */
     95     public static void CreateExcel(){
     96         
     97         //1.创建Excel工作薄对象
     98         HSSFWorkbook wb = new HSSFWorkbook();
     99         //2.创建Excel工作表对象     
    100         HSSFSheet sheet = wb.createSheet("new Sheet");
    101         //3.创建Excel工作表的行   
    102         HSSFRow row = sheet.createRow(6);
    103         //4.创建单元格样式
    104         CellStyle cellStyle =wb.createCellStyle();
    105           // 设置这些样式
    106         cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    107         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    108         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    109         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    110         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    111         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    112         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    113           
    114           
    115           
    116         //5.创建Excel工作表指定行的单元格
    117         row.createCell(0).setCellStyle(cellStyle);
    118         //6.设置Excel工作表的值
    119         row.createCell(0).setCellValue("aaaa");
    120         
    121         row.createCell(1).setCellStyle(cellStyle);
    122         row.createCell(1).setCellValue("bbbb");
    123         
    124         
    125         //设置sheet名称和单元格内容
    126         wb.setSheetName(0,"第一张工作表");
    127         //设置单元格内容    cell.setCellValue("单元格内容");
    128         
    129         // 最后一步,将文件存到指定位置
    130                 try
    131                 {
    132                     FileOutputStream fout = new FileOutputStream("E:/students.xls");
    133                     wb.write(fout);
    134                     fout.close();
    135                 }
    136                 catch (Exception e)
    137                 {
    138                     e.printStackTrace();
    139                 }
    140     }
    141     
    142     /**
    143      * 创建Excel的实例
    144      * @throws ParseException 
    145      */
    146     public static void CreateExcelDemo1() throws ParseException{
    147         List list = new ArrayList();
    148         SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
    149         Student user1 = new Student(1, "张三", 16,true, df.parse("1997-03-12"));
    150         Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));
    151         Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));
    152         list.add(user1);
    153         list.add(user2);
    154         list.add(user3);
    155         
    156         
    157         // 第一步,创建一个webbook,对应一个Excel文件
    158                 HSSFWorkbook wb = new HSSFWorkbook();
    159                 // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    160                 HSSFSheet sheet = wb.createSheet("学生表一");
    161                 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    162                 HSSFRow row = sheet.createRow((int) 0);
    163                 // 第四步,创建单元格,并设置值表头 设置表头居中
    164                 HSSFCellStyle style = wb.createCellStyle();
    165                 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    166 
    167                 HSSFCell cell = row.createCell((short) 0);
    168                 cell.setCellValue("学号");
    169                 cell.setCellStyle(style);
    170                 cell = row.createCell((short) 1);
    171                 cell.setCellValue("姓名");
    172                 cell.setCellStyle(style);
    173                 cell = row.createCell((short) 2);
    174                 cell.setCellValue("年龄");
    175                 cell.setCellStyle(style);
    176                 cell = row.createCell((short) 3);
    177                 cell.setCellValue("性别");
    178                 cell.setCellStyle(style);
    179                 cell = row.createCell((short) 4);
    180                 cell.setCellValue("生日");
    181                 cell.setCellStyle(style);
    182 
    183                 // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
    184 
    185                 for (int i = 0; i < list.size(); i++)
    186                 {
    187                     row = sheet.createRow((int) i + 1);
    188                     Student stu = (Student) list.get(i);
    189                     // 第四步,创建单元格,并设置值
    190                     row.createCell((short) 0).setCellValue((double) stu.getId());
    191                     row.createCell((short) 1).setCellValue(stu.getName());
    192                     row.createCell((short) 2).setCellValue((double) stu.getAge());
    193                     row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");
    194                     cell = row.createCell((short) 4);
    195                     cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
    196                             .getBirthday()));
    197                 }
    198                 // 第六步,将文件存到指定位置
    199                 try
    200                 {
    201                     FileOutputStream fout = new FileOutputStream("E:/students.xls");
    202                     wb.write(fout);
    203                     fout.close();
    204                 }
    205                 catch (Exception e)
    206                 {
    207                     e.printStackTrace();
    208                 }
    209         
    210         
    211         
    212     }
    213 }

    XSSF方式:

      1 package com.tools.poi.lesson1;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.FileNotFoundException;
      6 import java.io.FileOutputStream;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.io.OutputStream;
     10 import java.text.ParseException;
     11 import java.text.SimpleDateFormat;
     12 import java.util.ArrayList;
     13 import java.util.List;
     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.hssf.util.HSSFColor;
     21 import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
     22 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
     23 import org.apache.poi.ss.usermodel.Cell;
     24 import org.apache.poi.ss.usermodel.CellStyle;
     25 import org.apache.poi.ss.usermodel.Row;
     26 import org.apache.poi.ss.usermodel.Sheet;
     27 import org.apache.poi.ss.usermodel.Workbook;
     28 import org.apache.poi.ss.usermodel.WorkbookFactory;
     29 import org.apache.poi.ss.util.WorkbookUtil;
     30 
     31 import com.tools.poi.bean.Student;
     32 
     33 public class ExcelUtilWithXSSF {
     34     public static void main(String[] args) {
     35         try {
     36             getExcelAsFile("d:/FTP/系统报表.xls");
     37         } catch (FileNotFoundException e) {
     38             e.printStackTrace();
     39         } catch (IOException e) {
     40             e.printStackTrace();
     41         } catch (InvalidFormatException e) {
     42             e.printStackTrace();
     43         }
     44         
     45         
     46 //        try {
     47 //            CreateExcelDemo1();
     48 //        } catch (ParseException e) {
     49 //            e.printStackTrace();
     50 //        }
     51         
     52         
     53     }
     54     
     55     /**
     56      * 得到Excel,并解析内容  对2007及以上版本 使用XSSF解析
     57      * @param file
     58      * @throws FileNotFoundException
     59      * @throws IOException
     60      * @throws InvalidFormatException 
     61      */
     62     public static void getExcelAsFile(String file) throws FileNotFoundException, IOException, InvalidFormatException{
     63 //        //1.得到Excel常用对象
     64 //        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream("d:/FTP/new1.xls"));
     65 //        //2.得到Excel工作簿对象
     66 //        HSSFWorkbook wb = new HSSFWorkbook(fs);
     67 
     68         
     69         
     70         InputStream ins = null;   
     71         Workbook wb = null;   
     72             ins=new FileInputStream(new File(file));   
     73             //ins= ExcelService.class.getClassLoader().getResourceAsStream(filePath);   
     74             wb = WorkbookFactory.create(ins);   
     75             ins.close();   
     76         
     77         
     78         //3.得到Excel工作表对象
     79         Sheet sheet = wb.getSheetAt(0);
     80         //总行数
     81         int trLength = sheet.getLastRowNum();
     82         //4.得到Excel工作表的行
     83         Row row = sheet.getRow(0);
     84         //总列数
     85         int tdLength = row.getLastCellNum();
     86         //5.得到Excel工作表指定行的单元格
     87         Cell cell = row.getCell((short)1);
     88         //6.得到单元格样式
     89         CellStyle cellStyle = cell.getCellStyle();
     90 
     91         for(int i=5;i<trLength;i++){
     92             //得到Excel工作表的行
     93             Row row1 = sheet.getRow(i);
     94             for(int j=0;j<tdLength;j++){
     95             //得到Excel工作表指定行的单元格
     96             Cell cell1 = row1.getCell(j);
     97             /**
     98              * 为了处理:Excel异常Cannot get a text value from a numeric cell
     99              * 将所有列中的内容都设置成String类型格式
    100              */
    101             if(cell1!=null){
    102                   cell1.setCellType(Cell.CELL_TYPE_STRING);
    103              }
    104             
    105             if(j==5&&i<=10){
    106                 cell1.setCellValue("1000");
    107             }
    108             
    109             //获得每一列中的值
    110             System.out.print(cell1+"                   ");
    111             }
    112             System.out.println();
    113         }
    114         
    115         //将修改后的数据保存
    116         OutputStream out = new FileOutputStream(file);
    117                 wb.write(out);
    118     }
    119     
    120     
    121     /**
    122      * 创建Excel,并写入内容
    123      */
    124     public static void CreateExcel(){
    125         
    126         //1.创建Excel工作薄对象
    127         HSSFWorkbook wb = new HSSFWorkbook();
    128         //2.创建Excel工作表对象     
    129         HSSFSheet sheet = wb.createSheet("new Sheet");
    130         //3.创建Excel工作表的行   
    131         HSSFRow row = sheet.createRow(6);
    132         //4.创建单元格样式
    133         CellStyle cellStyle =wb.createCellStyle();
    134           // 设置这些样式
    135         cellStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
    136         cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
    137         cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
    138         cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
    139         cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
    140         cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
    141         cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    142           
    143           
    144           
    145         //5.创建Excel工作表指定行的单元格
    146         row.createCell(0).setCellStyle(cellStyle);
    147         //6.设置Excel工作表的值
    148         row.createCell(0).setCellValue("aaaa");
    149         
    150         row.createCell(1).setCellStyle(cellStyle);
    151         row.createCell(1).setCellValue("bbbb");
    152         
    153         
    154         //设置sheet名称和单元格内容
    155         wb.setSheetName(0,"第一张工作表");
    156         //设置单元格内容    cell.setCellValue("单元格内容");
    157         
    158         // 最后一步,将文件存到指定位置
    159                 try
    160                 {
    161                     FileOutputStream fout = new FileOutputStream("E:/students.xls");
    162                     wb.write(fout);
    163                     fout.close();
    164                 }
    165                 catch (Exception e)
    166                 {
    167                     e.printStackTrace();
    168                 }
    169     }
    170     
    171     /**
    172      * 创建Excel的实例
    173      * @throws ParseException 
    174      */
    175     public static void CreateExcelDemo1() throws ParseException{
    176         List list = new ArrayList();
    177         SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd");
    178         Student user1 = new Student(1, "张三", 16,true, df.parse("1997-03-12"));
    179         Student user2 = new Student(2, "李四", 17,true, df.parse("1996-08-12"));
    180         Student user3 = new Student(3, "王五", 26,false, df.parse("1985-11-12"));
    181         list.add(user1);
    182         list.add(user2);
    183         list.add(user3);
    184         
    185         
    186         // 第一步,创建一个webbook,对应一个Excel文件
    187                 HSSFWorkbook wb = new HSSFWorkbook();
    188                 // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    189                 HSSFSheet sheet = wb.createSheet("学生表一");
    190                 // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    191                 HSSFRow row = sheet.createRow((int) 0);
    192                 // 第四步,创建单元格,并设置值表头 设置表头居中
    193                 HSSFCellStyle style = wb.createCellStyle();
    194                 style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    195 
    196                 HSSFCell cell = row.createCell((short) 0);
    197                 cell.setCellValue("学号");
    198                 cell.setCellStyle(style);
    199                 cell = row.createCell((short) 1);
    200                 cell.setCellValue("姓名");
    201                 cell.setCellStyle(style);
    202                 cell = row.createCell((short) 2);
    203                 cell.setCellValue("年龄");
    204                 cell.setCellStyle(style);
    205                 cell = row.createCell((short) 3);
    206                 cell.setCellValue("性别");
    207                 cell.setCellStyle(style);
    208                 cell = row.createCell((short) 4);
    209                 cell.setCellValue("生日");
    210                 cell.setCellStyle(style);
    211 
    212                 // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
    213 
    214                 for (int i = 0; i < list.size(); i++)
    215                 {
    216                     row = sheet.createRow((int) i + 1);
    217                     Student stu = (Student) list.get(i);
    218                     // 第四步,创建单元格,并设置值
    219                     row.createCell((short) 0).setCellValue((double) stu.getId());
    220                     row.createCell((short) 1).setCellValue(stu.getName());
    221                     row.createCell((short) 2).setCellValue((double) stu.getAge());
    222                     row.createCell((short)3).setCellValue(stu.getSex()==true?"男":"女");
    223                     cell = row.createCell((short) 4);
    224                     cell.setCellValue(new SimpleDateFormat("yyyy-mm-dd").format(stu
    225                             .getBirthday()));
    226                 }
    227                 // 第六步,将文件存到指定位置
    228                 try
    229                 {
    230                     FileOutputStream fout = new FileOutputStream("E:/students.xls");
    231                     wb.write(fout);
    232                     fout.close();
    233                 }
    234                 catch (Exception e)
    235                 {
    236                     e.printStackTrace();
    237                 }
    238         
    239         
    240         
    241     }
    242 }
  • 相关阅读:
    Android渐变GradientDrawable叠加组合环ring
    72.spring boot讨论群【从零开始学Spring Boot】
    71.mybatis 如何获取插入的id【从零开始学Spring Boot】
    Android GradientDrawable的XML实现
    服务器端架构及实战 — C#分享
    70.打印所有Spring boot载入的bean【从零开始学Spring Boot】
    69. JPA实体Bean的生命周期【从零开始学Spring Boot】
    Android版网易云音乐唱片机唱片磁盘旋转及唱片机机械臂动画关键代码实现思路
    服务器架构及实战(架构篇)- PHP建站
    创建MyOffice项目
  • 原文地址:https://www.cnblogs.com/sunny-sl/p/7794249.html
Copyright © 2011-2022 走看看