java 通过poi操作excel

1代码


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 java.io.*;

public class POIUtil {
    /**
     * 读取一列,拼接成一个字符串
     * @param filePath 文件路径 xls格式的
     * @param col 第几列,从零开始
     * @throws IOException
     */
    public static void readColumn(String  filePath,int col) throws IOException {
        String nameList="";
        // 获取Excel文件
        File excelFile = new File(filePath);
        // 获取Excel工作簿
        InputStream inputStream = new FileInputStream(excelFile);
        Workbook workbook = new HSSFWorkbook(inputStream);
        Sheet sheet=workbook.getSheetAt(0);
        int rowEnd = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i <rowEnd ; i++) {
            Row row=sheet.getRow(i);
            Cell cell=row.getCell(col);
            String value= cell.getStringCellValue();
            nameList+=value+"、";
        }
        System.out.println(nameList);
        workbook.close();
    }

    /**
     * 向excel中写
     * @param filePath 模板文件路径
     * @param outPath 输出文件路径
     * @throws Exception
     */
    public static void write(String filePath,String outPath) throws Exception{
        // 获取Excel文件
        File excelFile = new File(filePath);
        // 获取Excel工作簿
        InputStream inputStream = new FileInputStream(excelFile);
        Workbook workbook = new HSSFWorkbook(inputStream);
        Sheet sheet0 = workbook.getSheetAt(0);
        Row row=sheet0.createRow(0);
        Cell cell=row.createCell(0);
        cell.setCellValue("你好");
        FileOutputStream fileOut = new FileOutputStream(outPath);
        workbook.write(fileOut);
        fileOut.close();
        workbook.close();

    }


}

2依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
    </dependencies>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值