Jaya Krishna
Jaya Krishna

Reputation: 313

Problems in creating excel sheets with java

I am trying to open a existing excel document and trying to create a sheet and insert data into the cells. When i compile my code in eclipse i am not getting any errors but when i run my code its not affecting the excel document.

Here is my code

import java.io.*;
import java.io.FileInputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFrame;
import javax.swing.JButton;
public class test{
 test()
{
    JFrame f = new JFrame("Pay Slip Generator");
    f.setVisible(true);
    f.setSize(500, 300);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setLayout( new FlowLayout() );
    JButton choose_file = new JButton("choose file");
    f.add(choose_file);
    choose_file.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent ae){
             JFileChooser fileopen = new JFileChooser();
                FileFilter filter = new FileNameExtensionFilter("c files", "c");
                fileopen.addChoosableFileFilter(filter);
                int ret = fileopen.showDialog(null, "Open file");
                if (ret == JFileChooser.APPROVE_OPTION) {
                  File file = fileopen.getSelectedFile();
                  String path = file.getAbsolutePath();
                  System.out.println(path);
                  try
                  {
                  FileInputStream fis = new FileInputStream(path);
                  HSSFWorkbook wb = new HSSFWorkbook(fis);
                  int no_sheets = wb.getNumberOfSheets();
                  System.out.println(no_sheets);
                  HSSFSheet sheet = wb.createSheet("test");
                  HSSFRow row = sheet.createRow(10);
                  HSSFCell cell = row.createCell(10);
                  cell.setCellValue("Hello");
                  fis.close();

                  }
                  catch(Exception e)
                  {
                      e.printStackTrace();
                  }
        }
    }
    });

    }
public static void main(String args[])throws IOException
{
    new test();

}

Looking forward for reply, thanks in advance.

Upvotes: 0

Views: 131

Answers (1)

MKay
MKay

Reputation: 836

It is not affecting, because you are not writing the data back to Excel. Insert below lines after :cell.setCellValue("Hello");

FileOutputStream out = new FileOutputStream(new File(path));
    wb.write(out);
    wb.close();
   out.close();

Make sure your excel file is not open while executing the code.

Upvotes: 2

Related Questions