poi批量修改Excel文件,修改工作表中的目標單元格資料

Walter Sun發表於2018-04-28

需要匯入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);
        }
    }
}

相關文章