Java读写Excel

1.引入POI依赖

2.

package com.cowcow.poi;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class MainClass {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        //MainClass.writeExcel("student.xlsx");
        MainClass.readExcel("student.xlsx");

    }

    public static void writeExcel(String url) throws IOException {

        Workbook workbook = null;

        if (url.endsWith("xls")) {
            workbook = new HSSFWorkbook();
        } else if (url.endsWith("xlsx")) {
            workbook = new XSSFWorkbook();
        } else {
            System.out.println("文件格式错误,请检查文件格式!");
        }

        Sheet sheet = workbook.createSheet("测试");

        Row row = sheet.createRow(0);

        Cell cell = row.createCell(0);
        cell.setCellValue("姓名");

        cell = row.createCell(1);
        cell.setCellValue("年龄");

        cell = row.createCell(2);
        cell.setCellValue("性别");

        cell = row.createCell(3);
        cell.setCellValue("住址");

        for (int i = 1; i <= 10; i++) {

            Row rowI = sheet.createRow(i);
            for (int j = 0; j < 4; j++) {
                rowI.createCell(j).setCellValue(j);
            }
        }

        FileOutputStream fos = new FileOutputStream(url);

        workbook.write(fos);
        workbook.close();
        fos.close();

    }

    public static void readExcel(String url) throws IOException {

        Workbook workbook = null;
        FileInputStream fis = new FileInputStream(url);
        if (url.endsWith("xls")) {
            workbook = new HSSFWorkbook(fis);
        } else if (url.endsWith("xlsx")) {
            workbook = new XSSFWorkbook(fis);
        } else {
            System.out.println("文件格式错误,请检查文件格式!");
        }

        Sheet sheet = workbook.getSheetAt(0);
        Row row = sheet.getRow(0);
        int start = row.getFirstCellNum();
        int end = row.getLastCellNum();
        System.out.println(start + "------" + end);
        for (int i = start; i < end; i++) {
            System.out.println(row.getCell(i).getStringCellValue());
        }

        workbook.close();
        fis.close();

    }

}
以上为简单读写Excel

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值