zoukankan      html  css  js  c++  java
  • Java POI读取Excel数据,将数据写入到Excel表格

    1.准备

    首先需要导入poi相应的jar包,包括:

    下载地址:http://pan.baidu.com/s/1bpoxdz5

    所需要的包的所在位置包括:

     

    2.读取Excel数据代码

      1 package Shape2MDB;
      2 
      3 import java.io.File;
      4 import java.io.FileInputStream;
      5 import java.io.InputStream;
      6 import java.util.ArrayList;
      7 import java.util.List;
      8 
      9 import org.apache.poi.hssf.usermodel.HSSFCell;
     10 import org.apache.poi.hssf.usermodel.HSSFRow;
     11 import org.apache.poi.hssf.usermodel.HSSFSheet;
     12 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
     13 import org.apache.poi.xssf.usermodel.XSSFCell;
     14 import org.apache.poi.xssf.usermodel.XSSFRow;
     15 import org.apache.poi.xssf.usermodel.XSSFSheet;
     16 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
     17 
     18 import Bean.Student;
     19 
     20 public class ReadXMLXData {
     21  public static void main(String[] args) {
     22   String path = "D:\1work\XLSX\Test.xlsx";
     23   if (path.endsWith(".xls")) {
     24    readExcel2003(path);
     25   } else if (path.endsWith(".xlsx")) {
     26    readExcel2007(path);
     27   }
     28  }
     29 
     30  private static void readExcel2007(String path) {
     31   File excelFile = null;// Excel文件对象
     32   InputStream is = null;// 输入流对象
     33   String cellStr = null;// 单元格,最终按字符串处理
     34   List<Student> studentList = new ArrayList<Student>();// 返回封装数据的List
     35   Student student = null;// 每一个学生信息对象
     36   try {
     37    excelFile = new File(path);
     38    is = new FileInputStream(excelFile);// 获取文件输入流
     39    XSSFWorkbook workbook2007 = new XSSFWorkbook(is);// 创建Excel2007文件对象
     40    XSSFSheet sheet = workbook2007.getSheetAt(0);// 取出第一个工作表,索引为0
     41    // 这里注意区分getLastRowNum()和getPhysicalNumberOfRows()的区别
     42    System.out.println("sheet.getLastRowNum():" + sheet.getLastRowNum());
     43    System.out.println("sheet.getPhysicalNumberOfRows():" + sheet.getPhysicalNumberOfRows());
     44    // 开始循环遍历行,表头不处理,从1开始
     45    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
     46     student = new Student();// 实例化Student对象
     47     XSSFRow row = sheet.getRow(i);// 获取行对象
     48     if (row == null) {// 如果为空,不处理
     49      continue;
     50     }
     51     // row如果不为空,循环遍历单元格
     52     for (int j = 0; j < row.getLastCellNum(); j++) {
     53      XSSFCell cell = row.getCell(j);// 获取单元格对象
     54      if (cell == null) {// 单元格为空设置cellStr为空串
     55       cellStr = "";
     56      } else if (cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {// 对布尔值的处理
     57       cellStr = String.valueOf(cell.getBooleanCellValue());
     58      } else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {// 对数字值的处理
     59       cellStr = cell.getNumericCellValue() + "";
     60      } else {// 其余按照字符串处理
     61       cellStr = cell.getStringCellValue();
     62      }
     63 
     64      // 下面按照数据出现位置封装到bean中
     65      if (j == 0) {
     66       student.setName(cellStr);
     67      } else if (j == 1) {
     68       student.setGender(cellStr);
     69      } else if (j == 2) {
     70       student.setAge(new Double(cellStr).intValue());
     71      } else if (j == 3) {
     72       student.setSclass(cellStr);
     73      } else {
     74       student.setScore(new Double(cellStr).intValue());
     75      }
     76     }
     77     studentList.add(student);// 数据装入List
     78    }
     79    System.out.println(studentList);
     80 
     81   } catch (Exception e) {
     82    e.printStackTrace();
     83   } finally {// 关闭文件流
     84    try {
     85     if (is != null) {
     86      is.close();
     87     }
     88    } catch (Exception e2) {
     89     e2.printStackTrace();
     90    }
     91   }
     92  }
     93 
     94  private static void readExcel2003(String path) {
     95   File excelFile = null;// Excel文件对象
     96   InputStream is = null;// 输入流对象
     97   String cellStr = null;// 单元格,最终按字符串处理
     98   List<Student> studentList = new ArrayList<Student>();// 返回封装数据的List
     99   Student student = null;// 每个学生信息对象
    100   try {
    101    excelFile = new File(path);
    102    is = new FileInputStream(excelFile);// 获取文件输入流
    103    HSSFWorkbook workbook2003 = new HSSFWorkbook(is);// 创建Excel2003文件对象
    104    HSSFSheet sheet = workbook2003.getSheetAt(0);// 取出第一个工作表,索引是0
    105    // 这里注意区分getLastRowNum()和getPhysicalNumberOfRows()的区别
    106    System.out.println("sheet.getLastRowNum():" + sheet.getLastRowNum());
    107    System.out.println("sheet.getPhysicalNumberOfRows():" + sheet.getPhysicalNumberOfRows());
    108    // 开始循环遍历行,表头不处理,从1开始
    109    for (int i = 1; i <= sheet.getLastRowNum(); i++) {
    110     student = new Student();// 实例化Student对象
    111     HSSFRow row = sheet.getRow(i);// 获取行对象
    112     if (row == null) {// 如果为空,不处理
    113      continue;
    114     }
    115     // 如果row不为空,循环遍历单元格
    116     System.out.println("row.getLastCellNum:" + row.getLastCellNum());
    117     for (int j = 0; j < row.getLastCellNum(); j++) {
    118      HSSFCell cell = row.getCell(j);// 获取单元格对象
    119      if (cell == null) {// 如果为空,设置cellStr为空串
    120       cellStr = "";
    121      } else if (cell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN) {// 对布尔值的处理
    122       cellStr = String.valueOf(cell.getBooleanCellValue());
    123      } else if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {// 对数字值的处理
    124       cellStr = cell.getNumericCellValue() + "";
    125      } else {// 其余按照字符串处理
    126       cellStr = cell.getStringCellValue();
    127      }
    128 
    129      // 下面按照数据出现的位置封装到bena中
    130      if (j == 0) {
    131       student.setName(cellStr);
    132      } else if (j == 1) {
    133       student.setGender(cellStr);
    134      } else if (j == 2) {
    135       student.setAge(new Double(cellStr).intValue());
    136      } else if (j == 3) {
    137       student.setSclass(cellStr);
    138      } else {
    139       student.setScore(new Double(cellStr).intValue());
    140      }
    141     }
    142     studentList.add(student);// 数据装入List
    143    }
    144    System.out.println(studentList);
    145   } catch (Exception e) {
    146    e.printStackTrace();
    147   } finally {// 关闭文件流
    148    if (is != null) {
    149     try {
    150      is.close();
    151     } catch (Exception e2) {
    152      e2.printStackTrace();
    153     }
    154    }
    155   }
    156  }
    157 }

    3.将数据写入到Excel表格代码

     1 package Shape2MDB;
     2 
     3 import java.io.FileOutputStream;
     4 import java.text.SimpleDateFormat;
     5 import java.util.ArrayList;
     6 import java.util.List;
     7 
     8 import org.apache.poi.hssf.usermodel.HSSFCell;
     9 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
    10 import org.apache.poi.hssf.usermodel.HSSFRow;
    11 import org.apache.poi.hssf.usermodel.HSSFSheet;
    12 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    13 
    14 import Bean.Student;
    15 
    16 public class OutputXMLSData {
    17  public static void main(String[] args) {
    18   //测试数据
    19   List<Student> list = new ArrayList<Student>();
    20   Student s1 = new Student("1", "1", 1, "1", 1);
    21   list.add(s1);
    22   Student s2 = new Student("1", "1", 1, "1", 1);
    23   list.add(s2);
    24   Student s3 = new Student("1", "1", 1, "1", 1);
    25   list.add(s3);
    26   Student s4 = new Student("1", "1", 1, "1", 1);
    27   list.add(s4);
    28   Student s5 = new Student("1", "1", 1, "1", 1);
    29   list.add(s5);
    30   Student s6 = new Student("1", "1", 1, "1", 1);
    31   list.add(s6);
    32   outPutData(list);
    33  }
    34 
    35  private static void outPutData(List<Student> list) {
    36   // 第一步,创建一个webbook,对应一个Excel文件
    37   HSSFWorkbook wb = new HSSFWorkbook();
    38   // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    39   HSSFSheet sheet = wb.createSheet("学生表一");
    40   // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    41   HSSFRow row = sheet.createRow((int) 0);
    42   // 第四步,创建单元格,并设置值表头 设置表头居中
    43   HSSFCellStyle style = wb.createCellStyle();
    44   style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
    45 
    46   HSSFCell cell = row.createCell((short) 0);
    47   cell.setCellValue("name");
    48   cell.setCellStyle(style);
    49   cell = row.createCell((short) 1);
    50   cell.setCellValue("gerder");
    51   cell.setCellStyle(style);
    52   cell = row.createCell((short) 2);
    53   cell.setCellValue("age");
    54   cell.setCellStyle(style);
    55   cell = row.createCell((short) 3);
    56   cell.setCellValue("class");
    57   cell.setCellStyle(style);
    58   cell = row.createCell((short) 4);
    59   cell.setCellValue("score");
    60   cell.setCellStyle(style);
    61 
    62   // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
    63 
    64   for (int i = 0; i < list.size(); i++) {
    65    row = sheet.createRow((int) i + 1);
    66    Student stu = (Student) list.get(i);
    67    // 第四步,创建单元格,并设置值
    68    row.createCell((short) 0).setCellValue(stu.getName());
    69    row.createCell((short) 1).setCellValue(stu.getGender());
    70    row.createCell((short) 2).setCellValue((double) stu.getAge());
    71    row.createCell((short) 3).setCellValue(stu.getSclass());
    72    row.createCell((short) 2).setCellValue((double) stu.getScore());
    73   }
    74   // 第六步,将文件存到指定位置
    75   try {
    76    FileOutputStream fout = new FileOutputStream("C:/students.xls");
    77    wb.write(fout);
    78    fout.close();
    79   } catch (Exception e) {
    80    e.printStackTrace();
    81   }
    82 
    83  }
    84 }

    4.异常处理

    Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/xmlbeans/XmlException
     at Shape2MDB.ReadXMLXData.readExcel2007(ReadXMLXData.java:39)
     at Shape2MDB.ReadXMLXData.main(ReadXMLXData.java:26)
    Caused by: java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlException
     at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
     at java.security.AccessController.doPrivileged(Native Method)
     at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
     at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
     at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
     ... 2 more

    使用POI操作Excel,电脑上面装的office2007,一直报如下错误,第一个是反射有关的,第二个是没找到对应的类,确实在POI的几个包中也没有找到该类,但是我直接引入该类编译器又没报错……最后发现把Excel另存为2003的格式是就正确了。到网上查了下,在操作office2007还要加入一个包
    xbean.jar   官网:http://xmlbeans.apache.org  

    本文也提供网盘下载地址:http://pan.baidu.com/s/1bQI3jK

    4.POI报表的一些常用函数

    摘自:http://blog.csdn.net/tolcf/article/details/48346697

    (1)建立sheet:

        1.HSSFSheet sheet = workbook.createSheet("sheet1");//新建sheet页

    (2)兴建单元格:

             2.HSSFCellStyle cellStyle = wb.createCellStyle();  //新建单元格样式 

    (3)  设置背景颜色:

    1. cellStyle.setFillForegroundColor((short) 13);// 设置背景色    
    2. cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);  

    (4)设置边框:

    1. cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); //下边框    
    2. cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//左边框    
    3. cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//上边框    
    4. cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//右边框    

    (5)设置居中:cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 居中   

    (6)设置字体:

    1. HSSFFont font2 = wb.createFont();    
    2. font2.setFontName("仿宋_GB2312");    
    3. font2.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//粗体显示    
    4. font2.setFontHeightInPoints((short) 12);  //字体大小  
    5. cellStyle.setFont(font);//选择需要用到的字体格式 

    (7)设置列宽

    1. sheet.setColumnWidth(0, 3766);   
    2. //第一个参数代表列id(从0开始),第2个参数代表宽度值  参考 :"2012-08-10"的宽度为2500 

    (8)设置自动换行

    1. cellStyle.setWrapText(true);//设置自动换行   

    (9)合并单元格

    1. //参数1:行号 参数2:起始列号 参数3:行号 参数4:终止列号    
    2. Region region1 = new Region(0, (short) 0, 0, (short) 6);//合并第(0,0)单元格到第(0,6)单元格  
    3. sheet.addMergedRegion(region1);  
    4. //此方法在POI3.8中已经被废弃,建议使用下面一个   
    5. //或者用  
    6. CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11); //参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列   
    7. sheet.addMergedRegion(region1);  
    8. //但应注意两个构造方法的参数不是一样的,具体使用哪个取决于POI的不同版本。

                                                                                                                                                                          

  • 相关阅读:
    Python 强制停止多线程运行
    自动化测试 Appium之Python运行环境搭建 Part2
    自动化测试 Appium之Python运行环境搭建 Part1
    Genymotion Android模拟器Genymotion的安装和使用
    Easyui datagrid combobox输入框下拉(取消)选值和编辑已选值处理
    性能测试 接口性能测试需要注意的点
    Python 基于Python及zookeeper实现简单分布式任务调度系统设计思路及核心代码实现
    lintcode:整数排序||
    lintcode:整数排序
    lintcode:玩具工厂
  • 原文地址:https://www.cnblogs.com/dz-boss/p/6734623.html
Copyright © 2011-2022 走看看