I am working on creating an excel report from java code using apache POI library. I have encountered a problem while formatting excel cell. Please find below piece of code.
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("coverageData");
int rownum = 0,cellnum=0;
Row row1 = sheet.createRow(rownum++);
Cell cell10 = row1.createCell(cellnum++);
cell10.setCellValue("cell data");
XSSFCellStyle row1style = (XSSFCellStyle)cell10.getCellStyle();
XSSFColor grayColor = new XSSFColor(Color.DARK_GRAY);
row1style.setFillBackgroundColor(grayColor);
cell10.setCellStyle(row1style);
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("P:\\automation\\Spreadsheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Spreadsheet.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
The problem here is i am setting cell10 style in last line of code, but it is not getting affected in the excel sheet created by the program.
Thanks in advance.
Try it, bellow work fine for me:
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.usermodel.XSSFWorkbook;
public class TestClass {
public static void main(String[] args){
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("coverageData");
int rownum = 0,cellnum=0;
Row row1 = sheet.createRow((short)rownum++);
//Set Color style start
CellStyle row1style = wb.createCellStyle();
row1style.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.getIndex());
row1style.setFillPattern(CellStyle.BIG_SPOTS);
//Set Color style end
Cell cell10 = row1.createCell((short)cellnum++);
cell10.setCellStyle(row1style);
cell10.setCellValue("cell data");
try{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Spreadsheet.xlsx"));
wb.write(out);
out.close();
System.out.println("Spreadsheet.xlsx written successfully on disk.");
} catch (Exception e) { e.printStackTrace(); }
}
}
You need to set the color like this:
final XSSFCellStyle description = (XSSFCellStyle) workbook.createCellStyle();
description.setFillForegroundColor( yourColor );
description.setFillPattern( FillPatternType.SOLID_FOREGROUND );
This is, you need a fill pattern
Related
I'm trying to copy an existing excel sheet to the same workbook(it contains 3 sheets ) in java using Apache poi .
Here is what i did :
FileInputStream file = new FileInputStream(new File("work.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet_copy = workbook.cloneSheet(0);
int num = workbook.getSheetIndex(sheet_copy);
workbook.setSheetName(num, "copy_file");
after running this code, the workbook contains always 3 sheets , the "copy_file" is not created, i'm not getting any errors or exceptions .
any idea ?
You need to open an output stream and write to the workbook. Make sure to close the workbook and the output stream after this write operation.
Demo:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Main {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("work.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet_copy = workbook.cloneSheet(0);
int num = workbook.getSheetIndex(sheet_copy);
workbook.setSheetName(num, "copy_file");
file.close();
FileOutputStream outputStream = new FileOutputStream("work.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
}
}
Requirement
i need to open excel file. Then i need to check for the date(12/31/2014). If this exist in the file then i need replace with 11/28/2014. Actually excel file is containing the date. But in my code is never passing this condition if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {.
Here is the code:
package excelAsOfDate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelAsOfDate {
public static void main(String[] args) {
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Date newAsOfDate = df.parse("11/28/2014");
System.out.println("date as of" + df.format(asOfDate));
File directory = new File("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".xlsx")) {
FileInputStream fis = new FileInputStream(file.getAbsoluteFile());
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(fis);
int i = 1;
while (i < workbook.getNumberOfSheets()) {
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(i);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {
// System.out.println(df.format(cell.getDateCellValue()));
System.out.println(df.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy"));
cell.setCellValue(newAsOfDate);
cell.setCellStyle(cellStyle);
}
}
break;
}
}
}
i++;
fis.close();
}
//FileOutputStream fileOut = new FileOutputStream("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test//final//"+file.getName());
FileOutputStream fileOut = new FileOutputStream(file.getAbsoluteFile());
workbook.write(fileOut);
fileOut.close();
fis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Logging is a key to find your answers.
As I look into the Cell class, I see there is a method named :
getDateCellCalue()
When we look at the setter of that :
void setCellValue(java.util.Date value)
Converts the supplied date to its equivalent Excel numeric value and sets that into the cell.
So you are not comparing correct.
Mine quick suggestion is :
if (df.format(cell.getDateCellValue()).equals(df.format(asOfDate)))
If this doesn't work, put logging on what the df.format(cell.getDateCellValue() produces as String.
Edit :
Did you also noticed this :
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Your second date is MM/dd/yyyy
I am storing some files in excel sheet using java. I need to color the name of column. how can i process this. I want to color different columns with different colors.
resultMap.put("Question", question);
resultMap.put("Option a", options.get(0));
resultMap.put("Option b", options.get(1));
resultMap.put("Option c", options.get(2));
resultMap.put("Option d", options.get(3));
Question, option a, option b, option c, option d are five columns that I am storing. excel sheet is in .xlsx format
XSSFWorkbook myWorkBook = new XSSFWorkbook ();
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.createSheet(sheetName);
XSSFRow row = mySheet.createRow(0);
row.createCell(7).setCellValue("Question");
row.createCell(8).setCellValue("Option a");
row.createCell(9).setCellValue("Option b");
row.createCell(10).setCellValue("Option c");
row.createCell(11).setCellValue("Option d");
FileOutputStream fileOut = new FileOutputStream(outputFilePath);
myWorkBook.write(fileOut);
fileOut.close();
myWorkBook.close();
Assuming you are using Apache POI, you can do something like the below, or check this page for additional info and examples: http://poi.apache.org/spreadsheet/quick-guide.html#FillsAndFrills
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
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.xssf.usermodel.XSSFWorkbook;
public class ExCell {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
Workbook myWorkBook = new XSSFWorkbook();
Sheet mySheet = myWorkBook.createSheet("Main");
Row row = mySheet.createRow(0);
Font font = myWorkBook.createFont();
font.setColor(IndexedColors.BLUE.getIndex());
CellStyle style = myWorkBook.createCellStyle();
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
style.setFont(font);
Cell newCell = row.createCell(7);
newCell.setCellValue("Question");
newCell.setCellStyle(style);
row.createCell(8).setCellValue("Option a");
row.createCell(9).setCellValue("Option b");
row.createCell(10).setCellValue("Option c");
row.createCell(11).setCellValue("Option d");
FileOutputStream fileOut = new FileOutputStream("Sandeep.xlsx");
myWorkBook.write(fileOut);
fileOut.close();
myWorkBook.close();
System.out.println("Done");
}
}
I am writing a code to fetch data from an excel sheet and run selenium tests on it and write the output in a different excel file. But I am not able to view the output in the output file. I am getting error as excel found unreadable content in .xlsx message after java code.
package new_excel_package;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
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.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.eclipse.debug.core.model.MemoryByte;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class PoiReadExcelFile {
public static void main(String[] args) {
try {
WebDriver driver = new FirefoxDriver();
FileInputStream fileInputStream = new FileInputStream("D://new.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet worksheet = workbook.getSheet("check");
FileOutputStream fileOut = new FileOutputStream("D://test.xlsx",true);
XSSFWorkbook workbook_out = new XSSFWorkbook();
XSSFSheet worksheet_out = workbook_out.createSheet("Worksheet");
MemoryByte ms = new MemoryByte();
for(int i = 0; i < worksheet.getLastRowNum()+1;i++)
{
XSSFRow row = worksheet.getRow(i);
//System.out.println(row.toString());
int r = worksheet_out.getLastRowNum();
XSSFRow row1 = worksheet_out.createRow(r+1);
XSSFCell cell_user = row.getCell(0);
String user_names = cell_user.getStringCellValue();
CharSequence[] user_name = {cell_user.getStringCellValue()};
System.out.println("fetched username");
XSSFCell cell_mail = row.getCell(1);
String e_mails = cell_mail.getStringCellValue();
CharSequence[] e_mail = {cell_mail.getStringCellValue()};
System.out.println("fetched email");
driver.get("file:///D:/SANDEEP/html%20sample.html");
driver.findElement(By.name("Name")).sendKeys(user_name);
driver.findElement(By.name("Email")).sendKeys(e_mail);
driver.findElement(By.name("Submit")).click();
//String status = "done";
System.out.println("authenticated for" + user_names);
/*XSSFCell cell_user_out = row1.createCell(0);
cell_user_out.setCellValue(user_names.toString());
XSSFCell cell_mail_out = row1.createCell(1);
cell_user_out.setCellValue(e_mails.toString());
XSSFCell cell_stat_out = row1.createCell(2);
cell_user_out.setCellValue("done");*/
row1.createCell(0,i).setCellValue(user_names.toString());
row1.createCell(1,i).setCellValue(e_mails.toString());
row1.createCell(2,i).setCellValue("done");
System.out.println("user updated");
/*workbook_out.write(fileOut);
System.out.println("elements updated2");*/
}
//workbook.Save("D://test.xlsx",FileFormatType.Excel2007Xlsx);
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
driver.close();
System.out.println("elements updated");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am also reading the inputs from an excel document and writing the output in a separate excel(.xls) document. Unlike you, I have used HSSFWorkbook which only allows my output to be written in .xls but that should not impact the implementation.
The notable difference I can see is you are writing the workbook before closing the file as shown below:
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
This is how I implemented it:
HSSFWorkbook workbook = new HSSFWorkbook();
String fileName = "excelDoc\\" +(new SimpleDateFormat("dd-MM-yy--hh-mm-ss").format(Calendar.getInstance().getTime()))+ ".xls"; //relative location of file + Time stamp based file name (.xls)
System.out.println(fileName);
FileOutputStream file1 = new FileOutputStream (new File(fileName));
HSSFSheet spreadSheet = workbook.createSheet("Result Document");
HSSFRow row = spreadSheet.createRow((short) 0);
HSSFCell cell;
//Creating rows and filling them with data
cell = row.createCell(0);
cell.setCellValue(new HSSFRichTextString("Test No"));
cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("Test Result"));
//Please see below and compare
file1.close(); //Closing the file
FileOutputStream outFile =new FileOutputStream(new File(fileName)); //Creating new file
workbook.write(outFile); //printing the data in the new file
outFile.close(); //closing the new file
System.out.println("The Result are now printed in the excel sheet");
You're missing out this,
XSSFWorkbook workbook_out = new XSSFWorkbook(fileOut);
I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
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;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}