Java POI导入和导出Excel

1.引入依赖

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.15</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.15</version>
        </dependency>

2.读取、写入Excel文件

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

public class TestOperationExcel {

    private static String fileName = "F://demo.xlsx";

    public static void main(String[] args) throws Exception{
        createExcel();
        readExcel();
    }

    public static void createExcel() throws Exception {
        //创建一个excel文件,名称为:
        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建一个sheet,名称为工作簿1
        XSSFSheet sheet = workbook.createSheet("工作簿1");
        XSSFRow titleRow = sheet.createRow(0);

        XSSFCell nameCell = titleRow.createCell(0);
        nameCell.setCellValue("小诸葛的博客");

        XSSFCell idCell = titleRow.createCell(1);
        idCell.setCellValue("gdupa2015");

        FileOutputStream fileOutputStream = new FileOutputStream(fileName);
        workbook.write(fileOutputStream);
    }

    public static void readExcel() throws Exception {
        //1.获取excel文件
        XSSFWorkbook workbook = new XSSFWorkbook(fileName);
        //2.获取第一个工作表
        XSSFSheet sheet = workbook.getSheetAt(0);
        //3.获取工作表的第一行
        XSSFRow row1 = sheet.getRow(0);
        //4.获取第一行的第一列、第二列单元格
        XSSFCell cell1 = row1.getCell(0);
        XSSFCell cell2 = row1.getCell(1);
        //5.以字符串方式返回第一列单元格的内容
        String cell1Value = cell1.getStringCellValue();
        String cell2Value = cell2.getStringCellValue();
        System.out.println("name=>" + cell1Value);
        System.out.println("id=>" + cell2Value);

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值