Write data to Excel using Java

To write data to an Excel file using Java, you can use the Apache POI library. Here’s an example code snippet that demonstrates how to write data to an Excel file using Java:

import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelDataWriter {
    public static void main(String[] args) {
        String filePath = "/path/to/your/excel_file.xlsx";
        String sheetName = "Sheet1";

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet(sheetName);

            // Write data to cells
            Row row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue("Name");
            row1.createCell(1).setCellValue("Email");

            Row row2 = sheet.createRow(1);
            row2.createCell(0).setCellValue("John Doe");
            row2.createCell(1).setCellValue("[email protected]");

            // Save workbook to file
            try (FileOutputStream fos = new FileOutputStream(filePath)) {
                workbook.write(fos);
                System.out.println("Excel file created successfully.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Replace /path/to/your/excel_file.xlsx with the actual path to the Excel file you want to create.

This code uses the Apache POI library to create an Excel workbook (XSSFWorkbook), create a sheet within the workbook (createSheet()), and write data to cells using the setCellValue() method. In this example, it writes the headers “Name” and “Email” in the first row and “John Doe” and “[email protected]” in the second row.

Finally, the workbook is saved to the specified file path using a FileOutputStream. Make sure to include the Apache POI library (poi-.jar, poi-ooxml-.jar) in your classpath. You can download the library from the Apache POI website or include it as a Maven/Gradle dependency.

Pamai Tech
Turning ideas into Reality

Products

Office Add-in

Enterprise Solutions

Cloud Consulting

UI UX Design

Data Transformation

Services

FAQ's

Privacy Policy

Terms & Condition

Team

Contact Us

Company

About Us

Services

Features

Our Pricing

Latest News

© 2023 Pamai Tech