poi批量修改Excel文档,修改工作表中的目标单元格数据

2018-09-20 04:28 阅读 1,485 次 评论 0 条

需要导入poi的相关包。

maven的poi依赖:

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

Sheet sheet = wb.getSheetAt(2);//获取Excel的工作表sheet,下标从0开始。

int trLength = sheet.getLastRowNum();//获取Excel的行数

Row row = sheet.getRow(i);//获取Excel的行,下标从0开始

Cell cell = row.getCell(1);//获取指定单元格,单元格从左到右下标从0开始

package org.dom4j.io;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
 
public class ChangeExcelData {
 
    public static void main(String[] args) throws IOException, EncryptedDocumentException, InvalidFormatException {
        String path = "F:\\15xsd修改\\03_SMD";
        File folder = new File(path);
        //list()获取目录下所有文件 
        //list()获取目录下所有文件及目录的绝对路径
        //使用增强for遍历目录下文件(批量处理xml文件)
        InputStream excelFileInputStream = null;
        Workbook wb = null;
 
        for (File f : folder.listFiles()) {
            System.out.println("获取文件:" + f);
            //             创建 Excel 文件的输入流对象
            excelFileInputStream = new FileInputStream(f);
            //            FileOutputStream excelFileOutPutStream = new FileOutputStream(f);
            wb = WorkbookFactory.create(excelFileInputStream);
            excelFileInputStream.close();
 
            Sheet sheet = wb.getSheetAt(2);//获取Excel的工作表sheet,下标从0开始。
            int trLength = sheet.getLastRowNum();//获取Excel的行数
            for (int i = 0; i < trLength; i++) {
                Row row = sheet.getRow(i);//获取Excel的行,下标从0开始
                if (row == null) {//若行为空,则遍历下一行
                    continue;
                }
                Cell cell = row.getCell(1);//获取指定单元格,单元格从左到右下标从0开始
                if (cell != null
                        && cell.getStringCellValue().equals("N_DJHKYKWDCL")) {//获取单元格内容,作为String类型
                    System.out.println(cell);
                    cell.setCellValue("C_DJHKYKWDCL");//给单元格设值
                    System.out.println(cell);
                }
            }
            OutputStream out = new FileOutputStream(f);
            wb.write(out);
        }
    }
}

版权声明:本文著作权归原作者所有,欢迎分享本文,谢谢支持!
转载请注明:poi批量修改Excel文档,修改工作表中的目标单元格数据 | 雨晨博客
分类:JAVA, 程序笔记 标签:,

发表评论


表情