ใช้ Apache POI เขียนไฟล์ XLS, XLSX

ใช้ Apache POI เขียนไฟล์ XLS, XLSX

ใช้ WorkbookFactory เพื่อที่เราจะสามารถทำงานได้ทั้ง XLS และ XLSX

สิ่งที่ต้องระวัง คือ ถ้า แถว หรือ cell ที่เราจะเขียนลงไปมันไม่อยู่ใน range ที่มีข้อมูลอยู่แล้ว เราจะเขียนลงไปไม่ได้
นั่นคือ ก่อนที่จะเขียน เราต้อง get ROW นั้นขึ้นมา จากนั้น get CELL นั้น ขึ้นมาด้วย ถ้า ROW หรือ CELL เป็น null
เราต้องสร้าง ROW หรือ CELL นั้นขึ้นมาก่อน ถึงจะทำงานได้

import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;

public class ExcelModifier {

    public static void main(String[] args) {
        // --- 1. กำหนดค่าเริ่มต้น ---
        String inputFilePath = "C:/path/to/your/file.xlsx"; // <-- *** แก้ไขเป็นที่อยู่ไฟล์ของคุณ ***
        String newValue = "This is the new value!"; // ค่าใหม่ที่ต้องการใส่ใน Cell A1

        // --- 2. รับการตัดสินใจจาก User ---
        Scanner scanner = new Scanner(System.in);
        System.out.println("ต้องการบันทึกทับไฟล์เดิมหรือไม่? (yes/no):");
        String choice = scanner.nextLine().trim().toLowerCase();
        scanner.close();

        boolean overwrite = choice.equals("yes");

        try {
            // --- 3. เปิดไฟล์ Excel ด้วย WorkbookFactory ---
            System.out.println("กำลังเปิดไฟล์: " + inputFilePath);
            File inputFile = new File(inputFilePath);
            // ใช้ FileInputStream เพื่ออ่านไฟล์
            FileInputStream fis = new FileInputStream(inputFile);

            // WorkbookFactory จะสร้าง Workbook ที่เหมาะสม (HSSFWorkbook หรือ XSSFWorkbook) ให้เอง
            // การใช้ try-with-resources จะช่วยปิด Workbook และ Stream อัตโนมัติ
            try (Workbook workbook = WorkbookFactory.create(fis)) {
                
                // --- 4. แก้ไขข้อมูลใน Cell A1 ---
                // เลือกชีตแรก (index ที่ 0)
                Sheet sheet = workbook.getSheetAt(0);

                // เข้าถึงแถวแรก (Row 1 คือ index 0)
                // ถ้าแถวไม่มีอยู่ ให้สร้างขึ้นมาใหม่
                Row row = sheet.getRow(0);
                if (row == null) {
                    row = sheet.createRow(0);
                }

                // เข้าถึงเซลล์แรก (Cell A คือ index 0)
                // ถ้าเซลล์ไม่มีอยู่ ให้สร้างขึ้นมาใหม่
                Cell cell = row.getCell(0);
                if (cell == null) {
                    cell = row.createCell(0);
                }

                // ตั้งค่าใหม่ให้กับเซลล์
                cell.setCellValue(newValue);
                System.out.println("แก้ไข Cell A1 เป็นค่า: \"" + newValue + "\" เรียบร้อยแล้ว");

                // ปิด FileInputStream หลังจากอ่านเสร็จ
                fis.close();

                // --- 5. บันทึกไฟล์ ---
                String outputFilePath;
                if (overwrite) {
                    // กรณีทับไฟล์เดิม: ใช้ path เดิม
                    outputFilePath = inputFilePath;
                    System.out.println("กำลังบันทึกทับไฟล์เดิม...");
                } else {
                    // กรณีสร้างไฟล์ใหม่: สร้างชื่อไฟล์ใหม่
                    outputFilePath = generateNewFileName(inputFilePath);
                    System.out.println("กำลังบันทึกเป็นไฟล์ใหม่: " + outputFilePath);
                }

                // ใช้ FileOutputStream เพื่อเขียนไฟล์
                try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
                    workbook.write(fos);
                }

                System.out.println("บันทึกไฟล์สำเร็จ!");
            }

        } catch (IOException e) {
            System.err.println("เกิดข้อผิดพลาดในการอ่านหรือเขียนไฟล์: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("เกิดข้อผิดพลาดที่ไม่คาดคิด: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Helper method to create a new file name like "file_modified.xlsx"
     */
    private static String generateNewFileName(String originalPath) {
        int dotIndex = originalPath.lastIndexOf('.');
        if (dotIndex == -1) {
            return originalPath + "_modified";
        }
        String name = originalPath.substring(0, dotIndex);
        String extension = originalPath.substring(dotIndex);
        return name + "_modified" + extension;
    }
}