Writing to Excel with Java - java

I've searched around forums without prevail, so here I am.
I'm attempting to implement a method which writes to Excel, but every time it just corrupts the file. Here's a snippet of my code:
public static XSSFSheet printToExcel (ArrayList<String> al, Workbook wb, XSSFSheet s, FileWriter fw) throws FileNotFoundException, IOException {
int numOfRows = s.getPhysicalNumberOfRows();
for (int i = 0; i <= numOfRows; i++ ) {
XSSFRow row = s.createRow(i);
XSSFCell cell = row.createCell(i);
String text = al.get(i);
cell.setCellValue(text);
fw.write(text);
fw.close();
}
return s;
}
Hopefully you all can help me. I'm mostly self-taught so any advice will be appreciated.

This is an example which I wrote in another context but it will help you to start
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Hyperlink;
import org.apache.poi.xssf.usermodel.*;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WriteExcelBasic {
public static void main(String[] args) throws IOException {
String excelFileName = "/Users/home/Test3.xlsx";
FileOutputStream fos = new FileOutputStream(excelFileName);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFCellStyle style = wb.createCellStyle();
XSSFSheet sheet = wb.createSheet("sheet");
XSSFFont urlFont = wb.createFont();// changed lines
urlFont.setFontHeight((short)(9*20));
// urlFont.setUnderline((byte)10);
//urlFont.setBold(true);
urlFont.setFontName("Arial");
urlFont.setItalic(true);
urlFont.setColor(new XSSFColor(Color.BLUE)); // changed lines
style.setFont(urlFont);
for (int r = 0; r < 3; r++) {
XSSFRow row = sheet.createRow(r);
for (int c = 0; c < 3; c++) {
XSSFCell cell = row.createCell(c);
Hyperlink link = wb.getCreationHelper().createHyperlink(HyperlinkType.URL);
String ss = "http://news.google.com/news/headlines?ned=us&hl=en";
//String ss = "swasdqde";
link.setAddress(ss);
cell.setHyperlink(link);
cell.setCellValue(ss);
if(r == 1) {
System.out.println("In yellow");
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(Color.YELLOW));
} else {
System.out.println("In red");
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillForegroundColor(new XSSFColor(Color.RED));
}
cell.setCellStyle(style);
}
}
try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
wb.write(baos);
byte[] myByteArray = baos.toByteArray();
fos.write(myByteArray);
fos.flush();
}
finally {
wb.close();
fos.close();
}
}
}

Related

How to Delete or Remove empty rows in Excel sheet using java

Input Excel file.....
25010082512 25002207512 1044 1044 NGN NGN
36620841728 36617009228 1066 1066 NGN NGN
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class RemoveEmptyCellInExcel {
//shifting empty columns
public static void shift(File f){
File F=f;
HSSFWorkbook workbook = null;
HSSFSheet sheet=null;
Boolean isRowEmpty=false;
try{
FileInputStream is=new FileInputStream(F);
workbook= new HSSFWorkbook(is);
sheet = workbook.getSheetAt(0);
//sheet.setDisplayGridlines(false);
for(int i = 3; i < sheet.getLastRowNum(); i++){
if(sheet.getRow(i)==null){
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
continue;
}
for(int j=0; j<sheet.getRow(i).getLastCellNum();j++){
if(sheet.getRow(i).getCell(j).toString().trim().equals(""))
{
isRowEmpty=true;
}else {
isRowEmpty=false;
break;
}
}
if(isRowEmpty==true){
sheet.shiftRows(i+ 1, sheet.getLastRowNum(), -1);
i--;
}
}
//Writing output to the same file.
FileOutputStream fileOut = new FileOutputStream("--------");
workbook.write(fileOut);
fileOut.close();
System.out.println("Successfully wrote the content in the file");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String args[]) {
//Input file path
File f=new File("------------");
RemoveEmptyCellInExcel.shift(f);
}
}
I need following output.....
25010082512 25002207512 1044 1044 NGN NGN
36620841728 36617009228 1066 1066 NGN NGN
your code is over complicated try to simplifie try using apach csv :
public static void shift(File file){
final FileReader fr = new FileReader(file.getPath());
final File out = new File(path);
try(CSVPrinter printer = new CSVPrinter(out, CSVFormat.DEFAULT
.withDelimiter(' ')) {
final Iterable<CSVRecord> records =
CSVFormat.DEFAULT.withDelimiter(' ').parse(fr);
for (final CSVRecord record : records) {
printer.printRecord(record.get(0),record.get(1), ...,
record.get(record.size()-1));
}
Try to use this code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class RemoveEmptyCellInExcel {
//shifting empty columns
public static void shift(File f){
HSSFWorkbook workbook;
HSSFSheet sheet;
int firstColumn;
int endColumn;
boolean isRowEmpty = true;
try{
FileInputStream is=new FileInputStream(f);
workbook= new HSSFWorkbook(is);
sheet = workbook.getSheetAt(0);
//sheet.setDisplayGridlines(false);
//block to set column bounds
Iterator<Row> iter = sheet.rowIterator();
firstColumn = (iter.hasNext() ? Integer.MAX_VALUE : 0);
endColumn = 0;
while (iter.hasNext()) {
Row row = iter.next();
short firstCell = row.getFirstCellNum();
if (firstCell >= 0) {
firstColumn = Math.min(firstColumn, firstCell);
endColumn = Math.max(endColumn, row.getLastCellNum());
}
}
// main logic block
for (int i = 0; i< sheet.getLastRowNum(); i++) {
if (sheet.getRow(i) != null) {
isRowEmpty = true;
Row row = sheet.getRow(i);
for (int j = firstColumn; j < endColumn; j++) {
if (j >= row.getFirstCellNum() && j < row.getLastCellNum()) {
Cell cell = row.getCell(j);
if (cell != null) {
if (!cell.getStringCellValue().equals("")) {
isRowEmpty = false;
break;
}
}
}
}
//if empty
if (isRowEmpty) {
System.out.println("Found empty row on: " + row.getRowNum());
sheet.shiftRows(row.getRowNum() + 1, sheet.getLastRowNum(), -1);
i--;
}
}
// if row is null
else{
sheet.shiftRows(i + 1, sheet.getLastRowNum(), -1);
i--;
}
}
//Writing output to the same file.
FileOutputStream fileOut = new FileOutputStream("Test.xls");
workbook.write(fileOut);
fileOut.close();
System.out.println("Successfully wrote the content in the file");
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) {
//Input file path
File f=new File("Test.xls");
RemoveEmptyCellInExcel.shift(f);
}
}

Issue with reading data with apache POI. Data is read but excel file is corrupted afterwards

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelData {
File fs;
FileInputStream fis;
XSSFWorkbook workbook;
XSSFSheet sheet;
FileOutputStream fos;
public ExcelData(String datafile_path) throws Exception{
fs=new File(datafile_path);
fis=new FileInputStream(fs);
workbook=new XSSFWorkbook(fis);
fos=new FileOutputStream(fs);
public Object readData(int sheet_num, int row_num, int column_num) throws Exception{
sheet=workbook.getSheetAt(sheet_num);
//sheet.getRow(row_num).getCell(column_num).CELL_TYPE_STRING;
Object data = null;
if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_STRING){
data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
} else if (sheet.getRow(row_num).getCell(column_num).getCellType()==Cell.CELL_TYPE_NUMERIC){
data=sheet.getRow(row_num).getCell(column_num).getNumericCellValue();
}
workbook.close();
//String data=sheet.getRow(row_num).getCell(column_num).getStringCellValue();
workbook.close();
fis.close();
return data;
}
----This code is working in reading the data. All the data is read successfully but after execution when look at the file, it is corrupted and size is 0 kb from 10 kb.
Following snippet works for ".xls" file extension
public String[][] readFile(String filePath) throws IOException, BiffException {
int totalNoOfRows, totalNoOfCols;
FileInputStream fis = new FileInputStream(filePath);
Workbook wb = Workbook.getWorkbook(fis);
// To get the access to the sheet
Sheet sh = wb.getSheet("Sheet1");
// To get the number of rows present in sheet
totalNoOfRows = sh.getRows();
// To get the number of columns present in sheet
totalNoOfCols = sh.getColumns();
String[][] excelData = new String[totalNoOfRows][totalNoOfCols];
for (int row = 0; row < totalNoOfRows; row++) {
for (int col = 0; col < totalNoOfCols; col++) {
excelData[row][col] = sh.getCell(col, row).getContents();
}
}
wb.close();
fis.close();
return excelData;
}

Reading cells from an Existing Excel File and Writing them into a new Excel File using Java

So I'm currently creating a program to read, edit and place data from an existing Excel file into a new Excel File using the JXL Java library. At this stage I will just like to read data from the existing Excel file and place it into the new one. Can't seem to find a good way of doing it and for future work what is the best way to edit the data (having certain columns) and placing them into the new Excel File.
Sorry if anything is unclear, just getting grips with Java and Stackoverflow.
import java.io.*;
import jxl.*;
import jxl.write.Number;
import jxl.write.*;
class Extraction {
private String inputFile;
String data;
public void setInputFile(String inputFile){
this.inputFile = inputFile;
}
public void read() throws IOException {
File spreadsheet = new File(inputFile);
Workbook w;
try {
w = Workbook.getWorkbook(spreadsheet);
Sheet page = w.getSheet(0);
File f = new File("C:\\Users\\alex\\Desktop\\New_Export.xls");
if (!f.exists()){
String FileName = "C:\\Users\\alex\\Desktop\\New_Export.xls";
WritableWorkbook excel = Workbook.createWorkbook(new File(FileName));
WritableSheet sheet = excel.createSheet("Sheet1", 0);
for (int y = 0; y < page.getRows(); y++){
for (int x = 0; x < page.getColumns(); x++){
Cell cell = page.getCell(x ,y +1);
CellType type = cell.getType();
if(type == CellType.LABEL || type == CellType.NUMBER){
data = cell.getContents();
System.out.println(data);
//To now input the read data into the new Excel File
sheet.addCell();
}
}
System.out.println(" ");
}
System.out.println("The File Has Successfully Been Created!");
excel.write();
excel.close();
}
else{
System.err.println("File is already created!");
}
}
catch(Exception e){
System.out.println(" ");
}
}
public static void main (String args[]) throws IOException{
Extraction reading = new Extraction();
reading.setInputFile("C:\\Users\\alex\\Desktop\\export.xls");
reading.read();
}
}
Using the "poi" from apache, you can use the below code to read the excel (*.xls)
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
private void readingExcel(String fileName) {
try (FileInputStream file = new FileInputStream(new File(fileName))) {
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
for (Row row : sheet) {
Iterator<Cell> cellIterator = row.cellIterator();
for (Cell cell : row) {
System.out.println(cell.getStringCellValue());
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
For writing to excel
private File writingToExcel() {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample-sheet");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("My Sample Value");
File file = new File(sheet.getSheetName());
return file;
}
However, if you want to use *.xlsx, the class used to read is
XSSFWorkbook workbook = new XSSFWorkbook (file);
XSSFSheet sheet = workbook.getSheetAt(0);

writing a new cell to a sheet apache poi

i am using following code, for reading a excel using apache poi, its a .xlsx file. Please let me know what i can do, to also alter a value of a cell, in each row as my loop keeps going. Thanks
import java.io.FileInputStream;
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;
String fileName = "C:/createCDN.xlsx";
FileInputStream fis = null;
fis = new FileInputStream(fileName);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
FileOutputStream fos=new FileOutputStream(fileName);
XSSFSheet sheet = workbook.getSheetAt(0);
int totalRows=sheet.getLastRowNum();
for(int i=1;i<=totalRows;i++) {
XSSFRow row = sheet.getRow(i);
method.fillTextBox(row.getCell(0),"name", pageProp);
method.fillTextBox(row.getCell(0),"name", pageProp);
} //Do something here, or inside loop to write to lets say cell(2) of same row.
Thanks.
It should be like this:
for(int i = 1; i <= totalRows; i++) {
Row row = sheet.getRow(i);
Cell cell = row.getCell(2);
if (cell == null) {
cell = row.createCell(2);
}
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("some value");
}
To save the workbook you could just write:
FileOutputStream fos = new FileOutputStream(fileName);
workbook.write(fos);
fos.close();
You should take a look at POI's Busy Developers' Guide.
at first you need to create the space in the excel file, like this:
for(int row = 0; row < 10 ; row++) {
sheet.createRow(row);
for(int column = 0; column < 10; column++) {
sheet.getRow(row).createCell(column);
}
}
then you can write the excel using this command:
sheet.getRow(row).getCell(column).setCellValue("hello");

How To handle Null Row using Apache POI?

I am using Apache POI to read xlsx file, it works well. I have question to you when row is found null, how I'm able to handle it? My file contain 500 row, but it show 105667 row, rest of row found null.
used code:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* #author SAMEEK
*/
public class readXLSXFile {
public int getNumberOfColumn(String fileName, int sheetIndex) throws FileNotFoundException, IOException {
File inputFile = null;
FileInputStream fis = null;
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
XSSFRow row = null;
int lastRowNum = 0;
int lastCellNum = 0;
// Open the workbook
inputFile = new File(fileName);
fis = new FileInputStream(inputFile);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(sheetIndex);
lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < lastRowNum; i++) {
row = sheet.getRow(i);
if (row != null) {
if (row.getLastCellNum() > lastCellNum) {
lastCellNum = row.getLastCellNum();
}
}
}
return lastCellNum;
}
public int getNumberOfRow(String fileName, int sheetIndex) throws FileNotFoundException, IOException {
File inputFile = null;
FileInputStream fis = null;
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
int lastRowNum = 0;
// Open the workbook
inputFile = new File(fileName);
fis = new FileInputStream(inputFile);
workbook = new XSSFWorkbook(fis);
sheet = workbook.getSheetAt(sheetIndex);
lastRowNum = sheet.getLastRowNum();
return lastRowNum;
}
public String[] getSheetName(String fileName) throws FileNotFoundException, IOException {
int totalsheet = 0;
int i = 0;
String[] sheetName = null;
File inputFile = null;
FileInputStream fis = null;
XSSFWorkbook workbook = null;
// Open the workbook
inputFile = new File(fileName);
fis = new FileInputStream(inputFile);
workbook = new XSSFWorkbook(fis);
totalsheet = workbook.getNumberOfSheets();
sheetName = new String[totalsheet];
while (i < totalsheet) {
sheetName[i] = workbook.getSheetName(i);
i++;
}
return sheetName;
}
public int getNumberOfSheet(String fileName) throws FileNotFoundException, IOException {
int totalsheet = 0;
File inputFile = null;
FileInputStream fis = null;
XSSFWorkbook workbook = null;
XSSFSheet sheet = null;
int lastRowNum = 0;
// Open the workbook
inputFile = new File(fileName);
fis = new FileInputStream(inputFile);
workbook = new XSSFWorkbook(fis);
totalsheet = workbook.getNumberOfSheets();
return totalsheet;
}
public String[][] getSheetData(String fileName, int sheetIndex) throws FileNotFoundException, IOException, InvalidFormatException {
String[][] data = null;
int i = 0;
int j = 0;Cell cell=null;
long emptyrowcount = 0;
InputStream inputStream = new FileInputStream(
fileName);
// Create a workbook object.
Workbook wb = WorkbookFactory.create(inputStream);
wb.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
Sheet sheet = wb.getSheetAt(sheetIndex);
// Iterate over all the row and cells
int noOfColumns = getNumberOfColumn(fileName, sheetIndex);
System.out.println("noOfColumns::" + noOfColumns);
int noOfRows = getNumberOfRow(fileName, sheetIndex) + 1;
System.out.println("noOfRows::" + noOfRows);
data = new String[noOfRows][noOfColumns];
for (int k = 0; k < noOfRows; k++) {
Row row = sheet.getRow(k);
if (row == null) {
} else {
j = 0;
for (int l = 0; l < noOfColumns; l++) {
// Cell cell = cit.next();
cell = row.getCell(j);
if (cell.getCellType() == cell.CELL_TYPE_BLANK) {
cell = row.getCell(j, Row.CREATE_NULL_AS_BLANK);
}
data[i][j] = getCellValueAsString(cell);
j++;
}
i++;
}
}
return data;
}
/**
* This method for the type of data in the cell, extracts the data and
* returns it as a string.
*/
public static String getCellValueAsString(Cell cell) {
String strCellValue = null;
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
strCellValue = cell.toString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat(
"dd/MM/yyyy");
strCellValue = dateFormat.format(cell.getDateCellValue());
} else {
Double value = cell.getNumericCellValue();
Long longValue = value.longValue();
strCellValue = new String(longValue.toString());
}
break;
case Cell.CELL_TYPE_BOOLEAN:
strCellValue = new String(new Boolean(
cell.getBooleanCellValue()).toString());
break;
case Cell.CELL_TYPE_BLANK:
strCellValue = "";
break;
}
}
return strCellValue;
}
public static void main(String s[]) {
try {
readXLSXFile readXLSxFile = new readXLSXFile();
String[][] sheetData = readXLSxFile.getSheetData("F:/work.xlsx", 0);
int columnLength = 0;
columnLength = readXLSxFile.getNumberOfColumn("F:/work.xlsx", 0);
int rowLength = 0;
rowLength = readXLSxFile.getNumberOfRow("F:/work.xlsx", 0);
int h = 0;
int j = 0;
while (j < rowLength) {
h = 0;
while (h < columnLength) {
System.out.print("\t " + sheetData[j][h]);
h++;
}
System.out.println("");
j++;
}
} catch (InvalidFormatException ex) {
Logger.getLogger(readXLSFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (FileNotFoundException ex) {
Logger.getLogger(readXLSFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(readXLSFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Please help me how to handle null row in excel sheet?
If you fetch a row, and get back null, then that means there is no data stored in the file for that row - it's completely blank.
POI by default gives you what's in the file. With Cells, you can set a MissingCellPolicy to control how missing and blank cells are handled. There's some examples of using this in the Apache POI docs. With rows, they're either there or not, so you need to check for nulls when fetching a row.
In case your .xlsx file contains any of the formatting for the blank cells, the poi reading is not treating it as null, however if you want to print it's value, it will give NullPointerException. To understand it I have created a sheet and mark the first columns boundary with to "All Border" for 10 rows, but not given any value to it. now applying following piece of code is showing output sheet.lastRowNum() as 10, while the RowCountWithNullValue is 990, and RowCountWithoutNullValue is 10. However the sheet is completely blank. If you uncomment the print statement, it will show NullPointerException.
public class Rough {
public static void main(String args[]) throws IOException{
public static void main(String args[]) throws IOException{
FileInputStream fin = new FileInputStream(AddressOfxlsxFile);
XSSFWorkbook wb = new XSSFWorkbook(fin);
XSSFSheet sheet = wb.getSheetAt(1);
int RowCountWithNullValue=0, RowCountWithoutNullValue=0;
for (int i=0;i<1000;i++){
if (sheet.getRow(i)==null)
RowCountWithNullValue++;
else{
RowCountWithoutNullValue++;
// System.out.println(sheet.getRow(0).getCell(0));
}
}
System.out.println(sheet.getLastRowNum());
System.out.println(RowCountWithNullValue+","+RowCountWithoutNullValue);
}
}
I am not sure if the same is happening on your end or not, but if you are saying your file contain 500 row, but it show 105667 row, this may be one of the cause.

Categories