poi操作excel的基本用法

这周公司要用excel作为数据存储格式做一个文具申请的功能,感觉以前本来很简单的功能变复杂了不少,但是还是记录一下一些excel的基本用法。

写在最前面:这里只介绍一些excel的基本存储方式(读,写,数据和样式),高级用法并不会涉及。

首先是需要引入的jar包,如下表所示:(以下内容来自于Apache POI的官方文档)

Apache POI可以运用在许多文档文件的格式中。这些对文档操作的支持需要一些jar文件。不是所有的jar文件都被需要于每一个格式中。下面的表格列出了在POI部件中的关系,maven仓库的tags,和项目需要的jar文件。

组件 应用类型 Maven artifactId 注意
POIFS OLE2 Filesystem poi Required to work with OLE2 / POIFS based files
HPSF OLE2 Property Sets poi  
HSSF Excel XLS poi For HSSF only, if common SS is needed see below
HSLF PowerPoint PPT poi-scratchpad  
HWPF Word DOC poi-scratchpad  
HDGF Visio VSD poi-scratchpad  
HPBF Publisher PUB poi-scratchpad  
HSMF Outlook MSG poi-scratchpad  
DDF Escher common drawings poi  
HWMF WMF drawings poi-scratchpad  
OpenXML4J OOXML poi-ooxml plus either poi-ooxml-schemasor
ooxml-schemas and ooxml-security
See notes below for differences between these options
XSSF Excel XLSX poi-ooxml  
XSLF PowerPoint PPTX poi-ooxml  
XWPF Word DOCX poi-ooxml  
Common SL PowerPoint PPT and PPTX poi-scratchpad and poi-ooxml SL code is in the core POI jar, but implementations are in poi-scratchpad and poi-ooxml.
Common SS Excel XLS and XLSX poi-ooxml WorkbookFactory and friends all require poi-ooxml, not just core poi

下面是maven仓库所需要的jar包:

Maven artifactId 预先准备 JAR
poi commons-loggingcommons-codeclog4j poi-version-yyyymmdd.jar
poi-scratchpad poi poi-scratchpad-version-yyyymmdd.jar
poi-ooxml poipoi-ooxml-schemas poi-ooxml-version-yyyymmdd.jar
poi-ooxml-schemas xmlbeans poi-ooxml-schemas-version-yyyymmdd.jar
poi-examples poipoi-scratchpadpoi-ooxml poi-examples-version-yyyymmdd.jar
ooxml-schemas xmlbeans ooxml-schemas-1.3.jar
ooxml-security xmlbeans 
For signing: bcpkix-jdk15onbcprov-jdk15onxmlsecslf4j-api
ooxml-security-1.1.jar

综上可知:我们操作excel所需要poi,poi-ooxml和poi-ooxml-shemas这三类,请自行配置

tips:excel分为xls和xlsx,第一类是基于binary的标准,第二种是基于xml的规范,所以用不同的类进行操作

  • 新建一个excel文件:
/**
     * 新建一个excel 2003的文件,在项目的根目录下
     */
    public void createHSSFWorkBooksTest() {
        try {
            Workbook wb = new HSSFWorkbook(); //这里新建了一个exccel 2003的文件,所以
            //Workbook wb = new XSSFWorkbook();  这里是一个excel2007的文件,相应的输出流后缀应该是xlsx
            FileOutputStream fos = new FileOutputStream("workbook.xls");
            wb.write(fos);
            fos.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
  • 新建一个excel并且里面有2个sheet,一个叫做sheet1,一个叫做sheet2

    /**
         * 新建一个excel 2003的文件,在项目的根目录下
         */
        public void createHSSFWorkBooksTest() {
            try {
                Workbook wb = new HSSFWorkbook(); //这里新建了一个exccel 2003的文件,所以
                //Workbook wb = new XSSFWorkbook();  这里是一个excel2007的文件,相应的输出流后缀应该是xlsx
                FileOutputStream fos = new FileOutputStream("workbook.xls");
                wb.write(fos);
                fos.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
  • 在单元格里面赋值,值为1

tips:在单元格里面可以添加所有基本类型,以及公式,但是公式操作这里不做介绍

    /**
     * 在第二行的第一个单元格里面赋值,值为1
     * @throws Exception
     */
    public void testCreateCell() throws Exception {
        Workbook wb = new HSSFWorkbook();
        CreationHelper helper = wb.getCreationHelper();
        Sheet sheet = wb.createSheet("new Sheet");
        Row row = sheet.createRow(1);
        Cell cell = row.createCell(0);
        cell.setCellValue(1);
        FileOutputStream fos = new FileOutputStream("workbook.xls");
        wb.write(fos);
        fos.close();
    }
  • 在单元格里面添加日期类型
    /**
     * 在单元格里面添加日期类型的值
     * @throws Exception
     */
    public void testCreateDateCell() throws Exception {
        //新建一个excel2003的workbook
        Workbook wb = new HSSFWorkbook();
        //新建一个单元格
        Sheet sheet = wb.createSheet();
        CreationHelper helper = wb.getCreationHelper();
        //新建一行,且是第一行,java中的行是从0开始计算的
        Row row = sheet.createRow(0);
        //在第一行新建一个单元格
        Cell cell = row.createCell(0);
        //在这里赋一个没有转换格式的日期类型
        cell.setCellValue(new Date());
        //通过workbook获得一个cellstyle
        CellStyle style = wb.createCellStyle();
        //进行日期类型的格式转换
        style.setDataFormat(helper.createDataFormat().getFormat("m/d/yy h:mm"));
        //新建一个单元格,单元格的位置是第一行第二列
        cell = row.createCell(1);
        //赋值,变量为日期类型
        cell.setCellValue(new Date());
        //该单元格的style为上面的那种
        cell.setCellStyle(style);
        cell = row.createCell(2);
        //第二种获得日期的方法,通过调用java的canlendar
        cell.setCellValue(Calendar.getInstance());
        cell.setCellStyle(style);
        FileOutputStream fos = new FileOutputStream("workbook.xls");
        wb.write(fos);
        fos.close();
    }
  • 设置单元格里面的字体颜色
    /**
     * 设置不同的颜色显示
     * @throws Exception
     */
    public void testCreateDifferentCell() throws Exception {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("new sheet");
        Row row = sheet.createRow(2);
        CellStyle style = wb.createCellStyle();
        //获取一个font
        Font font = wb.createFont();
        //设置font的颜色为红色
        font.setColor(Font.COLOR_RED);
        style.setFont(font);
        row.createCell(0).setCellValue(1.2);
        row.getCell(0).setCellStyle(style);
        row.createCell(1).setCellValue(1);
        row.createCell(2).setCellValue(true);
        FileOutputStream fos = new FileOutputStream("workbook.xls");
        wb.write(fos);
        fos.close();
    }
  • 读取已经有的excel有两种方式:File和InputStream,但是在poi3.5之前不能用file的方式去读
/**
     * 读取已经存在excel的两种方式
     * File && InputStream
     *
     * @throws Exception
     */
    public void testCreateExcelByInputStreamAndFile() throws Exception {
        // Workbook wb = new HSSFWorkbook();
        Workbook wb = WorkbookFactory.create(new File("workbook.xls"));
        //Workbook wb = WorkbookFactory.create(new FileInputStream("workbook.xls"));
        Sheet sheet = wb.createSheet("new sheet");
        Row row = sheet.createRow(2);
        CellStyle style = wb.createCellStyle();
        // style.setFont(wb.createFont().setColor(Font.COLOR_RED));
        Font font = wb.createFont();
        font.setColor(Font.COLOR_RED);
        style.setFont(font);
        row.createCell(0).setCellValue(1.2);
        row.getCell(0).setCellStyle(style);
        row.createCell(1).setCellValue(1);
        row.createCell(2).setCellValue(true);
        wb.close();
        // FileOutputStream fos = new FileOutputStream("workbook.xls");
        // wb.write(fos);
        // fos.close();
    }
  • 循环excel里面所有的元素,默认的迭代方式,不用迭代器,但是在poi3.5之前都不支持这样的读取方式
    /**
     * 循环excel里面所有的元素,默认的迭代方式,不用迭代器,但是在poi3.5之前都不支持这样的读取方式
     * @throws Exception
     */
    public void testIterateAllExcel() throws Exception {
        Workbook wb = WorkbookFactory.create(new File("iterate.xls"));
        for (Sheet sheet : wb) {
            for (Row row : sheet) {
                for (Cell cell : row) {
                    if (cell == null) {
                        System.out.println("the cell is null!");
                    } else {
                        System.out.println(cell.getStringCellValue());

                    }
                }
            }
        }
        wb.close();
    }
  • 通过获取cell内容的类型来调用相应的方法获取cell里面的值
    /**
     * 在excel的单元格内容有各式各样的形式,所以读取之前要先判断读取内容的类型,然后才能用相应的方式读取出来
     * @throws Exception
     */
    public void testGetExcelContent() throws Exception {
        Workbook wb = WorkbookFactory.create(new File("iterate.xls"));
        Sheet sheet = wb.getSheetAt(0);
        for (Row row : sheet) {
            for (int i = 0; i < row.getLastCellNum(); i++) {
                //单元格的内容如果是空则返回null
                Cell cell = row.getCell(i, Row.RETURN_BLANK_AS_NULL);
                if (cell == null) {
                    System.out.println("the cell is null!");
                    continue;
                }
                //通过getCellType方法判断单元格里面的内容
                switch (cell.getCellType()) {
                //获取的内容为string类型
                case Cell.CELL_TYPE_STRING:
                    System.out.println("the type is String:"
                            + cell.getRichStringCellValue().getString());
                    break;
                //获取的内容为数字类型(包括整型,浮点...)
                case Cell.CELL_TYPE_NUMERIC:
                    System.out.println("the type is numeric:"
                            + cell.getNumericCellValue());
                    break;
                //获取的内容为布尔类型
                case Cell.CELL_TYPE_BOOLEAN:
                    System.out.println("the type is boolean:"
                            + cell.getBooleanCellValue());
                    break;
                //获取的内容为公式类型
                case Cell.CELL_TYPE_FORMULA:
                    System.out.println("the type is formula:"
                            + cell.getCellFormula());
                    break;
                //获取的内容为black
                case Cell.CELL_TYPE_BLANK:
                    System.out.println("the type is null:" + cell);
                    break;
                default:
                    System.out.println("-");
                    break;
                }
            }
        }
        wb.close();
    }
  • 读和重新写入
    /**
     * 读和重新写入,就是输入流和输出流都对同一个文件做操作
     * @throws Exception
     */
    public void testExcelFont() throws Exception {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet("new sheet");
        Row row = sheet.createRow((short) 1);
        Cell cell = row.createCell((short) 1);
        cell.setCellValue("This is testing merge");
        Font font = wb.createFont();
        font.setColor(IndexedColors.BLUE.getIndex());
        CellStyle style = wb.createCellStyle();
        style.setFont(font);
        cell.setCellStyle(style);
        FileOutputStream fos = new FileOutputStream("workbook.xls");
        wb.write(fos);
        wb.close();
        fos.close();
    }
时间: 2024-07-30 01:47:06

poi操作excel的基本用法的相关文章

java使用POI操作excel文件,实现批量导出,和导入

一.POI的定义 JAVA中操作Excel的有两种比较主流的工具包: JXL 和 POI .jxl 只能操作Excel 95, 97, 2000也即以.xls为后缀的excel.而poi可以操作Excel 95及以后的版本,即可操作后缀为 .xls 和 .xlsx两种格式的excel. POI全称 Poor Obfuscation Implementation,直译为"可怜的模糊实现",利用POI接口可以通过JAVA操作Microsoft office 套件工具的读写功能.官网:htt

(5) 如何用Apache POI操作Excel文件-----发现Apache的POI的Bug后,如何给Apache的POI报Bug?

在我上篇文章中,(4) 如何用Apache POI操作Excel文件-----发现了POI-3.12一个回归,通过测试POI-3.12的版本,我发现了一个bug,那么发现bug后,该如何处理.我们有2种处理方式,首先我们到Apache POI的bug库里面搜索,看别人有没有创建类似的bug,如果有创建的,这个是最好的结果,我们只需要关注这个bug什么时候被修复.如果没有搜索不到,这个时候我们就需要给Apache POI报bug了.那么,如何给Apache报Bug? 第一步: 打开https://

poi操作Excel工具类

在上一篇文章<使用poi读写Excel>中分享了一下poi操作Excel的简单示例,这次要分享一下我封装的一个Excel操作的工具类. 该工具类主要完成的功能是:读取Excel.写入Excel.合并Excel的功能.

JAVA使用POI操作excel

这里提一下,java操作excel的组件除了apache的poi,还有jexcelapi(jxl),其中poi组件的获取地址为poi.apache.org. poi组件中常用的类有HSSFworkbook表示一个完整的excel表格,HSSFsheet表示excel中的一个工作薄,HSSFRow表示工作薄中的一行,HSSFCell表示一个单元格 下面是一个简单的写入的demo public static void main(String [] args){ try { HSSFWorkbook

POI操作Excel详解,HSSF和XSSF两种方式

HSSF方式: package com.tools.poi.lesson1; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.

POI 操作Excel 异常org.apache.poi.openxml4j.exceptions.invalidformatexception: package should contain a c

POI 操作Excel 出现如下异常 org.apache.poi.openxml4j.exceptions.invalidformatexception: package should contain a content type part 代码如下 public boolean parseToExcel(String oldFileName,String newFileName){ Map<Object,Object> map = new HashMap<Object,Object&

POI操作EXCEL之导出Excel(设置有效性,下拉列表引用)

本人使用的是poi-bin-3.10-FINAL-20140208.zip 版本的poi以下是程序关键代码: //需要引用的类 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import ja

第七周作业 POI操作Excel,world文档

先来说说jxl与poi的区别. 相同点都是操作EXcel的工具,但jxl不常用原因有:jxl没有人维护,操作excel效力低下,只支持03及其以前的版本的excel,对图片的支持不完整. 同poi比较而言,poi效率高功能强大,支持xlsx,xls即支持所有的版本.而且操作大数据效率比较高,因为他对大数据的操作做了相应的优化. 下面来个简单地实现:poi操作Excel的功能 简单的单元测试类:实现的功能是向excel文件中写入数据 1 @Test 2 public void test1() th

POI操作Excel异常Cannot get a text value from a numeric cell

控制台抛出异常:java.lang.IllegalStateException: Cannot get a text value from a numeric cell 在java中用POI解析excel文件时出现以上报错,表示无法从一个数值类型的单元格获得文本类型的值. POI操作Excel时数据Cell有不同的类型,当我们试图从一个数字类型的Cell读取出一个字符串并写入数据库时,就会出现Cannot get a text value from a numeric cell的异常错误. 解决