POI实现excel的导入和导出

03最多是65536  xls 对象HSSFWorkbook

07没有限制 xlsx 对象XSSFWorkbook 升级版SXSSFWorkbook

工作博

工作表sheet

从0开始

<!--xls(03)-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.9</version>
</dependency>

<!--xls(07)-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.9</version>
</dependency>
<!--日期格式化工具-->
<dependency>
    <groupId>joda-time</groupId>
    <artifactId>joda-time</artifactId>
    <version>2.10.1</version>
</dependency>

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency>

生成Excel

POI的0.3版本       HSSFWorkbook

public class poi {

String PATH="E:\\删除";

@Test
public  void test03() throws Exception {
//        1.创建工作簿
    Workbook workbook=new HSSFWorkbook();
//        2.创建工作表
    Sheet sheet = workbook.createSheet("小郭测试");
//        3.创建一个行(1,1)
    Row row1 = sheet.createRow(0);
//        4.创建一个单元格
    Cell cell11 = row1.createCell(0);
    cell11.setCellValue("今日新增");
    Cell cell12 = row1.createCell(1);
    cell12.setCellValue("统计时间");

//        第二行(2,1)
    Row row2 = sheet.createRow(1);
    Cell cell21 = row2.createCell(0);
    cell21.setCellValue("50");
    //(2,2)
    Cell cell22 = row2.createCell(1);
    String time=new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    cell22.setCellValue(time);

    //生成一张表  03版本  使用xls结尾
    FileOutputStream fileOutputStream = new FileOutputStream(PATH + "03统计表.xls");
    workbook.write(fileOutputStream);
    //关闭流
    fileOutputStream.close();
    System.out.println("文件生成完毕!");


}

POI的0.7版本       XSSFWorkbook    后缀是xlsx

@Test
public  void test07() throws Exception {
//        1.创建工作簿
    Workbook workbook=new XSSFWorkbook();
//        2.创建工作表
    Sheet sheet = workbook.createSheet("小郭测试");
//        3.创建一个行(1,1)
    Row row1 = sheet.createRow(0);
//        4.创建一个单元格
    Cell cell11 = row1.createCell(0);
    cell11.setCellValue("今日新增");
    Cell cell12 = row1.createCell(1);
    cell12.setCellValue("统计时间");

//        第二行(2,1)
    Row row2 = sheet.createRow(1);
    Cell cell21 = row2.createCell(0);
    cell21.setCellValue("50");
    //(2,2)
    Cell cell22 = row2.createCell(1);
    String time=new DateTime().toString("yyyy-MM-dd HH:mm:ss");
    cell22.setCellValue(time);

    //生成一张表  03版本  使用xls结尾
    FileOutputStream fileOutputStream = new FileOutputStream(PATH + "07统计表.xlsx");
    workbook.write(fileOutputStream);
    //关闭流
    fileOutputStream.close();
    System.out.println("文件生成完毕!");


}

07的版本比较慢 用SXSSFWorkbook   

变化的地方是SXSSFWorkbook    对象  并且要记得清除临时文件

//清除临时文件
 ((SXSSFWorkbook) workbook).dispose();

读取Excel

和创建excel一样,注意下就可以了  这里只写了xls的版本

public class poi {
String PATH="E:\\删除\\";
@Test
public  void test03() throws Exception {
    //获取文件流
    FileInputStream fis=new FileInputStream(PATH+"删除03统计表.xls");
//        1.创建一个工作簿
    Workbook workbook=new HSSFWorkbook(fis);
//        2.得到表
    Sheet sheetAt = workbook.getSheetAt(0);
//        3.得到行
    Row row = sheetAt.getRow(0);
//        4.得到列
    Cell cell = row.getCell(0);
    System.out.println(cell.getStringCellValue());
    fis.close();
}

注意获取不同的数据类型

拿到所有的列

row.getPhysicalNumberOfCells();

拿到所有的行

sheet.getPhysicalNumberOfRows()

获取每一列的类型

cell.getCellType();

public class poi {
String PATH="E:\\删除\\";
@Test
public  void test03() throws Exception {
    //获取文件流
    FileInputStream fis=new FileInputStream(PATH+"删除03统计表.xls");
    Workbook workbook=new HSSFWorkbook(fis);
    Sheet sheet = workbook.getSheetAt(0);
//    获取标题内容
    Row rowTitle = sheet.getRow(0);
    if(rowTitle !=null){
        int cellCount = rowTitle.getPhysicalNumberOfCells();
        for(int cellNum=0;cellNum<cellCount;cellNum++){
            Cell cell = rowTitle.getCell(cellNum);
            if(cell !=null){
                int cellType = cell.getCellType();
                String cellValue = cell.getStringCellValue();
                System.out.print(cellValue+" |");
            }
        }
        System.out.println();
    }

//    获取表中的内容
    int rowCount = sheet.getPhysicalNumberOfRows();
    for (int rowNum = 0; rowNum < rowCount; rowNum++) {
        Row rowData = sheet.getRow(rowNum);
        if(rowData !=null){
            //读取列
            int cellCount=rowTitle.getPhysicalNumberOfCells();
            for(int cellNum=0;cellNum<cellCount;cellNum++){
                System.out.print("["+(rowNum+1)+"-"+(cellNum+1)+"]");
                Cell cell = rowData.getCell(cellNum);
//                匹配列的数据类型
                if(cell !=null){
                    int cellType = cell.getCellType();
                    String cellValue="";
                    switch (cellType){
                        case HSSFCell.CELL_TYPE_STRING://字符串
                            System.out.print("[String]");
                            cellValue=cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN://布尔
                            System.out.print("[BOOLEAN]");
                            cellValue=String.valueOf(cell.getBooleanCellValue());
                            break;
                        case HSSFCell.CELL_TYPE_BLANK://空
                            System.out.print("[BLANK]");
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC://数字(日期,普通数字)
                            System.out.print("[NUMERIC]");
                           if(HSSFDateUtil.isCellDateFormatted(cell)){
                               System.out.print("[日期]");
                               Date date = cell.getDateCellValue();
                               cellValue=new DateTime(date).toString("yyyy-MM-dd");
                           }else {
                                //不是日期格式.防止数字过长
                               System.out.println("[转换为字符串输出]");
                               cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                               cellValue=cell.toString();
                           }
                            break;
                        case HSSFCell.CELL_TYPE_ERROR://错误
                            System.out.print("[数据类型错误]");
                            break;
                    }
                    System.out.println(cellValue);
                }
            }
        }
    }
    fis.close();
}
}

EasyExcel的使用

导入jar包,记得将poi的依赖去掉

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>easyexcel</artifactId>
  <version>2.2.0-beta2</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
</dependency>

EasyExcel的创建

 

@Data
public class DemoData {
    @ExcelProperty("字符串标题")
    private String string;
    @ExcelProperty("日期标题")
    private Date date;
    @ExcelProperty("数字标题")
    private Double doubleData;
    /**
     * 忽略这个字段
     */
    @ExcelIgnore
    private String ignore;

}
public class EasyExcelDemo {
    String PATH="E:\\删除\\";

    private List<DemoData> data() {
        List<DemoData> list = new ArrayList<DemoData>();
        for (int i = 0; i < 10; i++) {
            DemoData data = new DemoData();
            data.setString("字符串" + i);
            data.setDate(new Date());
            data.setDoubleData(0.56);
            list.add(data);
        }
        return list;
    }

    @Test
    public  void simpleWrite(){
        String fileName = PATH + "EasyTest.xlsx";
        // 这里 需要指定写用哪个class去写,然后写到第一个sheet,名字为模板 然后文件流会自动关闭
        EasyExcel.write(fileName, DemoData.class).sheet("模板").doWrite(data());

    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JavaPOI是一个用于读取和写入Microsoft Office格式文件(如Excel、Word和PowerPoint)的开源Java库。使用JavaPOI可以实现Excel导入导出操作。下面是一个简单的示例代码,演示如何使用JavaPOI实现Excel导入导出功能: 1. 导入Excel文件: ```java import org.apache.poi.ss.usermodel.*; public class ExcelImporter { public static void main(String[] args) { try { Workbook workbook = WorkbookFactory.create(new File("path/to/excel/file.xlsx")); Sheet sheet = workbook.getSheetAt(0); for (Row row : sheet) { for (Cell cell : row) { // 处理单元格数据 String cellValue = cell.getStringCellValue(); System.out.print(cellValue + "\t"); } System.out.println(); } workbook.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 2. 导出Excel文件: ```java import org.apache.poi.ss.usermodel.*; public class ExcelExporter { public static void main(String[] args) { try { Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头 Row headerRow = sheet.createRow(0); headerRow.createCell(0).setCellValue("Name"); headerRow.createCell(1).setCellValue("Age"); headerRow.createCell(2).setCellValue("Email"); // 写入数据 Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue("John Doe"); dataRow.createCell(1).setCellValue(25); dataRow.createCell(2).setCellValue("johndoe@example.com"); FileOutputStream outputStream = new FileOutputStream("path/to/excel/file.xlsx"); workbook.write(outputStream); workbook.close(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码演示了使用JavaPOI导入导出Excel文件的基本操作。你可以根据自己的需求进行适当的修改和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

guoyebing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值