export jtable to excel in java netbeans [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
i have written the following code with some help from google for exporting jtable to excel but i am not able to export it to excel and i am also getting null pointer .
cell.setCellValue(model.getValueAt(i, j).toString());
the whole code is
try {
HSSFWorkbook fWorkbook = new HSSFWorkbook();
HSSFSheet fSheet;
fSheet = fWorkbook.createSheet("new Sheet");
HSSFFont sheetTitleFont = fWorkbook.createFont();
File file = new File("D:\\MOHIT\\bill report\\report.xls");
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//sheetTitleFont.setColor();
TableModel model = report_table.getModel();
TableColumnModel model1 = report_table.getTableHeader().getColumnModel();
HSSFRow fRow1 = fSheet.createRow((short) 0);
for (int i = 0; i < model1.getColumnCount(); i++){
HSSFCell cell = fRow1.createCell((short) i);
cell.setCellValue(model1.getColumn(i).getHeaderValue().toString());
}
for (int i = 1; i < model.getRowCount(); i++) {
HSSFRow fRow = fSheet.createRow((short) i);
for (int j = 1; j < model.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(model.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(file);
try (BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream)) {
fWorkbook.write(bos);
}
fileOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
can somebody tell me why am i getting null pointer exception how to correct it.

Try to replace
cell.setCellValue(model.getValueAt(i, j).toString());
by
cell.setCellValue(Objects.toString(model.getValueAt(i, j), ""));
And look the link which I've posted in my comment.
P.S. Class Objects is defined in the package java.util

Related

Update excel using Java

I am trying to update a column in the excel sheet but only the first row is getting update. The second iteration is not working. Could anyone help me on this? Below is my code that I am trying.
String excelPath = "path";
String YES = "Updated YES";
String NO = "Updated NO";
try {
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
Cell cell = null;
FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
HSSFSheet sheet1 = workSheet.getSheetAt(0);
String data = sheet1.getRow(i+1).getCell(i).toString();
if(data.equals(TCID.get(i))){
cell = sheet1.getRow(i+1).getCell(i+2);
cell.setCellValue(YES);
workSheet.write(output_file);
}else {
cell.setCellValue(NO);
workSheet.write(output_file);
}
}
fis.close();
output_file.close();
workSheet.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My latest code is below. Now it is updating the columns but the last row is not getting updated. What am i missing.
FileInputStream fis= new FileInputStream(excelPath);
HSSFWorkbook workSheet = new HSSFWorkbook(fis);
HSSFSheet sheet1 = workSheet.getSheetAt(0);
//FileOutputStream output_file =new FileOutputStream(excelPath);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
}
fis.close();
//output_file.close();
//workSheet.close();
FileOutputStream output_file =new FileOutputStream(excelPath);
workSheet.write(output_file);
output_file.close();
The row and the column are both keyed off 'i', so you'll be traversing the sheet diagonally.
But certainly do the things the other people are recommending too, they are all good suggestions.
Typically when working with a two dimensional block of information, I find it useful to have one loop for rows and then nested inside that a loop for columns (or vice versa)
e.g.
for (y = startRow; y <= maxRow; y++) {
....
for (x = startCol; x <= maxCol; x++) {
.... // do something to each column in the current row
cell = sheet1.getRow(y).getCell(x);
.....
Ok, so there are a couple of things.
Declare HSSFSheet sheet1 = workSheet.getSheetAt(0); outside of your loop. You are working with the same sheet each iteration of your for loop, so this only has to be invoked once.
Your logic to get the cell data (String data = sheet1.getRow(i+1).getCell(i).toString();) will not return you the same column. On your first iteration, you'll get (R)ow 1 : (C)olumn 0. The next iteration will return R2 : C1, then R2:C2, then R3:C3, etc. Notice the pattern that you are going diagonally down the columns, not vertically.
Rows start at 0.
You only need to workSheet.write(output_file); once you have done all your processing.
If the Row does not exist you will get a NullPointerException
As you are working with a unique Cell each iteration, you just declare it in the loop (so no need for Cell cell = null; outside your loop).
Here is a an example:
try {
FileInputStream fis = new FileInputStream(excelPath);
Workbook workbook = new HSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
for (int i = 0; i < 5; i++) {
Row row = sheet.getRow(i);
if (row != null) {
Cell cell = row.getCell(0);
cell.setCellValue("Updated cell.");
}
}
FileOutputStream output_file = new FileOutputStream(excelPath);
workbook.write(output_file);
output_file.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
I think moving Cell reference inside for loop should fix it for you.
Cell cell = null;
Also you might also need to move outside if-block incase you face NullPointerException in else-block
cell = sheet1.getRow(i+1).getCell(i+2)
Something like this...
HSSFSheet sheet1 = workSheet.getSheetAt(0);
for (int i = 0; i < TCID.size(); i++) {
String data = sheet1.getRow(i+1).getCell(0).toString();
Cell cell = sheet1.getRow(i+1).getCell(2);
if(data.equals(TCID.get(i))){
cell.setCellValue(YES);
}else {
cell.setCellValue(NO);
}
workSheet.write(output_file)
}

Apache POI Update Excel File After Adding Columns/Rows to JTable

New here so please be kind. I've spent a few hours trawling through posts trying to find an answer but no such luck.
I have an excel file that I import into a JTable and can then edit. Add columns, rows etc.
When I click the button to add a column or row they appear on the JTable as expected. However when I click the save button to save the file it hasn't added the new columns or rows to the Excel file.
I thought my save wasn't working correctly, but if I edit one of the two columns I already have saved in the Excel file the changes are saved to the Excel file so I am confused as to why I can edit the existing data in the file but any new rows or columns are not saved.
My export to excel is:
public void toExcel()
{
try
{
FileInputStream fsIP = new FileInputStream(new File("Recipes.xls"));
HSSFWorkbook fWorkbook = new HSSFWorkbook(fsIP);
HSSFSheet fSheet = fWorkbook.getSheet("RECIPES");
HSSFFont sheetTitleFont = fWorkbook.createFont();
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
TableColumnModel tcm = tables.getColumnModel();
HSSFRow fRow = fSheet.createRow((short) 0);
for(int j = 0; j < tcm.getColumnCount(); j++)
{
HSSFCell cell = fRow.createCell((int) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
for (int i = 0, row = 1; i < models.getRowCount(); i++, row++)
{
HSSFRow fRow1 = fSheet.createRow((short) row);
for (int j = 0; j < models.getColumnCount(); j++)
{
HSSFCell cell = fRow1.createCell((int) j);
cell.setCellValue(models.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream output_file = new FileOutputStream(new File("Recipes.xls"));
BufferedOutputStream bos = new BufferedOutputStream(output_file);
fWorkbook.write(output_file);
fWorkbook.close();
bos.close();
output_file.close();
}
catch(Exception e)
{
}
JOptionPane.showMessageDialog(
null, "Changes Saved",
"Confirmation",
JOptionPane.INFORMATION_MESSAGE);
}
My method for adding a column is as follows:
public void addNewRecipe()
{
models.addColumn(JOptionPane.showInputDialog("Enter A Description for Recipe"));
}
Thanks.
EDIT
Here is code for calling toExcel
saveButton.addActionListener(new ActionListener()
{
#Override public void actionPerformed(ActionEvent arg0)
{
{
models = new DefaultTableModel(datas, headers);
tableWidth = models.getColumnCount() * 150;
tableHeight = models.getRowCount() * 50;
tables.setPreferredSize(new Dimension( tableWidth, tableHeight));
tables.setModel(models);
tables.setRowHeight(50);
toExcel();
}
}
});

Why can't set a value for a row and column with the Apache POI?

I need to set a value for a specific row and column of the spreadsheet, but I get a null pointer before even i = 1. I've tried changing the code but this error keeps happening and I have no more idea why.Does anyone have any idea why this happens?
My code
public Workbook build(Planilha planilha) {
File file = new File(TEMPLATE_PATH);
if (!file.exists()) {
Log.error(this, String.format("File %s not exists.", file.getAbsolutePath()));
throw new NotFoundException("File not exists.");
}
Workbook wb = null;
try (FileInputStream fs = new FileInputStream(file)) {
wb = new XSSFWorkbook(fs);
wb = writeMetadatas(planilha, wb);
Map<String, Integer> header = getHeader(wb);
Sheet sheet = wb.getSheetAt(0);
Row row;
Cell cell;
for (int i = 0; i <= 10; i++) {
row = sheet.getRow(i);
for (int j = 0; j <= 10; j++) {
cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
if (cell.getColumnIndex() == 0 && row.getRowNum() == 7) {
cell.setCellValue("teste");
}
}
}
} catch (Exception e) {
Log.error(this, "Erro: Planilha não existe", e);
System.err.print("Erro");
}
String tmpDir = System.getProperty("java.io.tmpdir");
File f = FileUtil.file(PATH, System.currentTimeMillis() + ".xlsx");
try {
FileOutputStream fout = new FileOutputStream(f);
wb.write(fout);
fout.flush();
fout.close();
} catch (Exception e) {
Log.error(this, "Erro ao abrir arquivo p escrever.");
}
return wb;
}
**NullPointer happens in cell.setCellValue("teste");
I'm trying to set that cell
First, you can test if the row number is a certain number outside of your for loop that loops over the cells in a row. Pull that if outside your j for loop.
It looks like the Cell doesn't exist. row.getCell(j) is returning null.
You can use a MissingCellPolicy to determine whether you want to return a new Cell if the Cell doesn't already exist. The CREATE_NULL_AS_BLANK value will create a blank Cell for you if it doesn't already exist.

FileOutputStream (Apachhe POI) taking too long time to save

When I am edit a .xlsx file using Apache poi, its taking too long to save. The .xlsx file contains, formulas formatting and freeze pane. I am using the following code,
try {
FileInputStream file = new FileInputStream(new File(path));
XSSFWorkbook fWorkbook = new XSSFWorkbook(file);
XSSFSheet fSheet = fWorkbook.getSheetAt(0);
for(int i = 0; i < jTable1.getRowCount(); i++){
if(jTable1.getModel().getValueAt(i, index1).equals("1")){
XSSFCell cell = fSheet.getRow(i+1).getCell(index1);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(new Double(1));
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
cell =fSheet.getRow(i+1).getCell(index2);
cell.setCellValue(new Date());
cell.setCellStyle(cs);
}
}
file.close();
FileOutputStream fileOutputStream = new FileOutputStream(path);
fWorkbook.write(fileOutputStream);
fileOutputStream.close();
JOptionPane.showMessageDialog(this, "Data saved successfully.");
parent.removeContent();
}catch(Exception e){
e.printStackTrace();
}
Edit 1:
The excel file: http://ge.tt/5orGWSJ2/v/0?c
Loading Data into JTable from Excel:
try {
FileInputStream file1 = new FileInputStream(new File("c:\\sample.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file1);
XSSFSheet sheet = workbook.getSheetAt(0);
int rowc=sheet.getLastRowNum()+1;
int colc=sheet.getRow(0).getLastCellNum();
Object heading[] = new Object[colc+1];
XSSFRow row1 = sheet.getRow(0);
for(int i=0, column =0; i < colc; i++){
if(i == 1){
heading[column++] = "";
}
heading[column++] = cellToString(row1.getCell(i));
}
Object [][]j=new Object[rowc-1][colc+1];
for (int i = 1; i < rowc; i++) {
row1 = sheet.getRow(i);
for (int jj = 0, column = 0; jj < colc; jj++) {
if(column == 1){
j[i-1][column++] = new Boolean(false);
j[i-1][column] = cellToString(row1.getCell(jj));
}
else{
j[i-1][column]=cellToString(row1.getCell(jj));
}
column++;
}
}
jTable1.setModel(new DefaultTableModel(j, heading){
public Class getColumnClass(int columnIndex) {
if(columnIndex == 0){
return java.lang.Integer.class;
}
else if(columnIndex == 1){
return java.lang.Boolean.class;
}
else{
return java.lang.Object.class;
}
}
});
jTable1.getColumnModel().getColumn(1).setMaxWidth(60);
jTable1.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
jTable1.getTableHeader().setReorderingAllowed(false);
} catch (IOException ex) {
JOptionPane.showMessageDialog(BarcodePrint.this, ex);
}
Writing data into excel after editing column BarcodePrint:
try {
FileInputStream file = new FileInputStream(new File("c:\\sample.xlsx"));
XSSFWorkbook fWorkbook = new XSSFWorkbook(file);
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
Date currentdate = new Date();
XSSFSheet fsheet = fWorkbook.getSheetAt(0);
Double barcodeprintstatus = new Double(1);
int newindex = 24;
int printdate = 26;
int uniqueid = 27;
for(int i = 0; i < jTable1.getModel().getRowCount(); i++){
if(jTable1.getModel().getValueAt(i, newindex).equals("1")){
for(int k=1; k < fsheet.getPhysicalNumberOfRows(); k++){
XSSFCell cell = fsheet.getRow(k).getCell(uniqueid-1);
String uid = cell.getRawValue();
if(jTable1.getModel().getValueAt(i, uniqueid).toString().equals(uid)){
cell = (fsheet.getRow(i+1)).getCell(newindex-1);
cell.setCellType(XSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(barcodeprintstatus);
cell = fsheet.getRow(i+1).getCell(printdate-1);
cell.setCellValue(currentdate);
cell.setCellStyle(cs);
}
}
}
}
file.close();
FileOutputStream fileOutputStream = new FileOutputStream("c:\\sample.xlsx");
fWorkbook.write(fileOutputStream); // this is taking so much of time. Approximately 1 min.
fileOutputStream.close();
}catch(Exception e){
e.printStackTrace();
}
I am unable to solve this problem. fWorkbook.write(fileOutputStream); is taking so much of time as I mentioned above. Please help. Is there any other way to save the excel file? Or can I write data partially for a single column rather than the hole workbook?
Try to improve the code.
You call fSheet.getRow(i+1) twice. Try to introduce a variable and reuse the row rather than obtain it.
cell.setCellValue(new Double(1));
Create the 1 double once before the for loop and reuse it.
XSSFCellStyle cs = fWorkbook.createCellStyle();
cs.setDataFormat(fWorkbook.getCreationHelper().createDataFormat().getFormat("dd/MMMM/yyyy"));
Move the cell style creation and initializing out of the for loop. Create it before the loop and reuse.
cell.setCellValue(new Date());
Introduce a Date variable and create the Date just once. Again before the for loop.
Add a BufferedOutputStream around the FileOutputStream.

Exporting Jtable into the Excelsheet using HSSFWorkbook

Hello I am trying to Export Jtable Data into the Excel Sheet using HSSFWorkbook. and i am getting all the content what Table have but i am not getting Table Headers please can anyone help for the same.
Here the Command used for Taking content of the Jtable.
try {
HSSFWorkbook fWorkbook = new HSSFWorkbook();
HSSFSheet fSheet = fWorkbook.createSheet("new Sheet");
HSSFFont sheetTitleFont = fWorkbook.createFont();
File file = new File("/home/kishan/NetBeansProjects/JavaChecking/src/com/verve/SwingChecking/book.xls");
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//sheetTitleFont.setColor();
TableModel model = jTable1.getModel();
for (int i = 0; i < model.getRowCount(); i++) {
HSSFRow fRow = fSheet.createRow((short) i);
for (int j = 0; j < model.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(model.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream);
fWorkbook.write(bos);
bos.close();
fileOutputStream.close();
}catch(Exception e){
}
for (int i = 0; i < model.getColumnCount(); i++) {
HSSFRow fRow = fSheet.createRow((short) i);
for(int j = 0; j < model.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(model.getValueAt(i, j).toString());
System.out.println(model.getColumnName(j));
}
}
last for loop is not addind data of table header.
and i am getting this excel file
how to get Table header along with that??
Here's my implementation of the HSSF Workbook from the answers in this thread.
I created a class ExcelWriter then a Method Writer which takes two parameters; the JTable and the FileLocation to be used.
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author oluwajayi
*/
public class ExcelWriter {
public static void Writer (JTable jTable1, String Location) throws FileNotFoundException, IOException {
HSSFWorkbook fWorkbook = new HSSFWorkbook();
HSSFSheet fSheet = fWorkbook.createSheet("new Sheet");
HSSFFont sheetTitleFont = fWorkbook.createFont();
HSSFCellStyle cellStyle = fWorkbook.createCellStyle();
sheetTitleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//sheetTitleFont.setColor();
TableModel model = jTable1.getModel();
//Get Header
TableColumnModel tcm = jTable1.getColumnModel();
HSSFRow hRow = fSheet.createRow((short) 0);
for(int j = 0; j < tcm.getColumnCount(); j++) {
HSSFCell cell = hRow.createCell((short) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
cell.setCellStyle(cellStyle);
}
//Get Other details
for (int i = 0; i < model.getRowCount(); i++) {
HSSFRow fRow = fSheet.createRow((short) i+1);
for (int j = 0; j < model.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(model.getValueAt(i, j).toString());
cell.setCellStyle(cellStyle);
}
}
FileOutputStream fileOutputStream;
fileOutputStream = new FileOutputStream(Location);
try (BufferedOutputStream bos = new BufferedOutputStream(fileOutputStream)) {
fWorkbook.write(bos);
}
fileOutputStream.close();
}
}
Something like this to add Column Names in the first row of your sheet:
TableColumnModel tcm = jTable1.getColumnModel();
HSSFRow fRow = fSheet.createRow((short) 0);
for(int j = 0; j < tcm.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
You could run this first and then add the table data starting from the second row.
you are only writing the data in the TableModel to the workbook. This model does not contain the table header. Take a look at JTable.getTableHeader()
for example:
public class JTableExport {
public static void main(String[] args) {
Object[] columnNames = new Object[] {"column1", "column2"};
JTable table = new JTable(new Object[0][0], columnNames);
TableColumnModel model = table.getTableHeader().getColumnModel();
for (int i = 0; i < model.getColumnCount(); i++) {
System.out.println(model.getColumn(i).getHeaderValue());
}
}
}
this code prints
column1
column2
for(int j = 0; j < tcm.getColumnCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
for(int j = 0; j < tcm.getRowCount(); j++) {
HSSFCell cell = fRow.createCell((short) j);
cell.setCellValue(tcm.getColumn(j).getHeaderValue().toString());
}
I created this code:
public void Export() {
JFileChooser save = new JFileChooser();
save.setDialogTitle("Save as...");
save.setFileFilter(new FileNameExtensionFilter("xls", "xlsx", "xlsm"));
int choose = save.showSaveDialog(null);
if(choose == JFileChooser.APPROVE_OPTION) {
XSSFWorkbook export = new XSSFWorkbook();
XSSFSheet sheet1 = export.createSheet("new file");
try{
TableModel tableModel = showQuery.getModel();
for(int i=0; i<tableModel.getRowCount(); i++) {
XSSFRow newRow = sheet1.createRow(i);
for(int j=0; j<tableModel.getColumnCount(); j++) {
XSSFCell newCell = newRow.createCell((short) j);
if(i==0){
XSSFCellStyle style = export.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREY_40_PERCENT.getIndex());
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
newCell.setCellStyle(style);
newCell.setCellValue(tableModel.getColumnName(j));
} else {
XSSFCellStyle style = export.createCellStyle();
style.setBorderBottom(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
newCell.setCellStyle(style);
newCell.setCellValue(tableModel.getValueAt(i, j).toString());
}
}
}
FileOutputStream otp = new FileOutputStream(save.getSelectedFile()+".xlsx");
BufferedOutputStream bos = new BufferedOutputStream(otp);
export.write(bos);
bos.close();
otp.close();
JOptionPane.showMessageDialog(null, "Arquivo exprtado com sucesso!");
}catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
}

Categories