Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Set Direction to the Text in Cell using Java?
Next article icon

How to Write Data into Excel Sheet using Java?

Last Updated : 27 Nov, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report

Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class.

To do operations in excel sheets using JAVA, it comes in handy to use the CSV files because CSV files can easily be used with Microsoft Excel, Google spreadsheets, and almost all other spreadsheets available.

To write data into an excel sheet itself using poi :

1. Create a blank workbook.

XSSFWorkbook workbook = new XSSFWorkbook();

2. Create a sheet and name it.                                                                                                                                  

XSSFSheet spreadsheet = workbook.createSheet(" Student Data ");

3. Create a row                                                                                                                                                                    

Row row = sheet.createRow(rownum++);

4. Add cells to the sheet.

5. Repeat Steps 3 and 4 to write the complete data.

Prerequisite: Add all jar files downloaded from Apache POI download site in Java Program’s build path.

Example:

Java

// Java program to write data in excel sheet using java code
  
import java.io.File;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
  
public class WriteDataToExcel {
  
    // any exceptions need to be caught
    public static void main(String[] args) throws Exception
    {
        // workbook object
        XSSFWorkbook workbook = new XSSFWorkbook();
  
        // spreadsheet object
        XSSFSheet spreadsheet
            = workbook.createSheet(" Student Data ");
  
        // creating a row object
        XSSFRow row;
  
        // This data needs to be written (Object[])
        Map<String, Object[]> studentData
            = new TreeMap<String, Object[]>();
  
        studentData.put(
            "1",
            new Object[] { "Roll No", "NAME", "Year" });
  
        studentData.put("2", new Object[] { "128", "Aditya",
                                            "2nd year" });
  
        studentData.put(
            "3",
            new Object[] { "129", "Narayana", "2nd year" });
  
        studentData.put("4", new Object[] { "130", "Mohan",
                                            "2nd year" });
  
        studentData.put("5", new Object[] { "131", "Radha",
                                            "2nd year" });
  
        studentData.put("6", new Object[] { "132", "Gopal",
                                            "2nd year" });
  
        Set<String> keyid = studentData.keySet();
  
        int rowid = 0;
  
        // writing the data into the sheets...
  
        for (String key : keyid) {
  
            row = spreadsheet.createRow(rowid++);
            Object[] objectArr = studentData.get(key);
            int cellid = 0;
  
            for (Object obj : objectArr) {
                Cell cell = row.createCell(cellid++);
                cell.setCellValue((String)obj);
            }
        }
  
        // .xlsx is the format for Excel Sheets...
        // writing the workbook into the file...
        FileOutputStream out = new FileOutputStream(
            new File("C:/savedexcel/GFGsheet.xlsx"));
  
        workbook.write(out);
        out.close();
    }
}
                      
                       

Output:



Next Article
How to Set Direction to the Text in Cell using Java?
author
mishraaditya20142014
Improve
Article Tags :
  • Java
  • Java Programs
  • Technical Scripter
  • Technical Scripter 2020
Practice Tags :
  • Java

Similar Reads

  • How to Read Write Object's Data in CSV Format Using Notepad in Java?
    The CSV stands for Comma-Separated Values. CSV files can be used with almost any spreadsheet program, such as Microsoft Excel or Google Spreadsheets. They differ from other spreadsheet file types because you can only have a single sheet in a file, they can not save cell, column, or row. Also, you ca
    8 min read
  • How to Format the Text in a Word Document using Java?
    Apache POI is a project run by the Apache Software Foundation, and previously a sub-project of the Jakarta Project provides pure Java libraries for reading and writing files in Microsoft Office formats, such as Word, PowerPoint, and Excel. First do install Apache in order to import modules as per th
    3 min read
  • How to Add Hyperlink to the Contents of a Cell using Java?
    Add a hyperlink to a content of the cell using Java and Apache POI. Apache POI is a Java library that is used to handle Microsoft Office Documents. Installation: There are two ways to install the Apache POI dependency in our java project: Download below mentioned Jar files from poi.apache.org/downlo
    2 min read
  • How to Set Direction to the Text in Cell using Java?
    Apache POI is an open-source library by Apache which can be used to create, modify and display files MS office file in Java. It provides classes and methods to do so. This API provides various components such as POIFS (Poor Obfuscation Implementation File System), HSSF (Horrible Spreadsheet Format),
    3 min read
  • How to Apply Fonts to the Contents of a Cell Using Java?
    In this article, we will learn how to apply the custom font and various styles associated with it using Java and Apache POI (a Java API which is very useful to handle the Microsoft Documents). Approach: Writing a file using POI is very simple and involve following steps: Create a workbook.Create a s
    2 min read
  • How to Create a File with a Specific charset in Java?
    In Java, when we write text to a file, we must provide the character encoding to create a file with a specified charset. Classes to generate Java Files with Specified CharsetUsing a FileOutputStream and the OutputStreamWriter class we can generate a Java file with a specified charset. FileOutputStre
    2 min read
  • How to Apply Different Styles to a Cell in a Spreadsheet using Java?
    Apache POI is a powerful API that enables the user to create, manipulate, and display various file formats based on Microsoft Office using java programs. Using POI, one should be able to perform create, modify, and display/read operations on the following file formats. For Example, Java doesn’t prov
    6 min read
  • Java Program to Draw a Shape in Excel Sheet using Apache POI
    Apache POI supports customized printing by allowing users to select a range of cells in order to configure the desired print area in a worksheet using Java Program. The top-most shape is the patriarch. This is not visible on the sheet at all. To start drawing you need to call createPatriarch on the
    4 min read
  • Java Program to Write into a File
    FileWriter class in Java is used to write character-oriented data to a file as this class is character-oriented because it is used in file handling in Java. There are many ways to write into a file in Java as there are many classes and methods which can fulfill the goal as follows: Using writeString
    6 min read
  • How to Create Different Types of Cells in a Spreadsheet using Java?
    Apache POI is an API which was provided by Apache Foundation and is used to set the various type of values to the cell. The overloading function setCellValue() of Apache POI is used to set the value type of the cell. Maven is a powerful project management tool that is based on POM (project object mo
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences