I would like to dynamically generate multiple worksheets for a workbook/excel in Apache poi. I want to know how can I do it an efficient and thread safe/concurrent way.
So multiple worksheet dynamically with the option to name them.
Each worksheet will have their own set of columns etc ( or style).
Write return those back in a servlet etc.
Please help.
Thank you.
like this?
public static void createExcel(String excelFilePath, String sheetName)
throws IOException {
FileOutputStream fos = null;
try {
HSSFWorkbook workbook = null;
if (new File(excelFilePath).createNewFile()) {
workbook = new HSSFWorkbook();
} else {
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream(
new File(excelFilePath)));
workbook = new HSSFWorkbook(pfs);
}
if (workbook.getSheet(sheetName) == null) {
fos = new FileOutputStream(excelFilePath);
workbook.createSheet(sheetName);
workbook.write(fos);
}
} catch (IOException e) {
throw e;
} finally {
if (fos != null) {
fos.close();
}
}
}
Please find the sample code.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelUtility {
public static boolean writeDataSheetWise(final String excelFileName, final List<String> headers,
Map<String, List<Object[]>> sheetRowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
for(String sheetName: sheetRowDataList.keySet()) {
createSheet(workbook, sheetName, headers, sheetRowDataList.get(sheetName));
}
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
public static boolean writeData(final String excelFileName, final String sheetName, final List<String> headers,
List<Object[]> rowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
createSheet(workbook, sheetName, headers, rowDataList);
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
#SuppressWarnings("deprecation")
private static void createSheet(final HSSFWorkbook workbook, final String sheetName, final List<String> headers,
final List<Object[]> rowDataList) {
HSSFSheet sheet = workbook.createSheet(sheetName);
int rowCount = 0;
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont headersFont = workbook.createFont();
headersFont.setFontName(HSSFFont.FONT_ARIAL);
headersFont.setFontHeightInPoints((short) 16);
headersFont.setColor(HSSFColor.GREEN.index);
headersFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(headersFont);
// Creating header row
Row headerRow = sheet.createRow(rowCount++);
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(headers.get(i));
sheet.autoSizeColumn(i);
}
for (Object rowDataObject[] : rowDataList) {
Row row = sheet.createRow(rowCount++);
int cellnum = 0;
for (Object rowData : rowDataObject) {
Cell cell = row.createCell(cellnum++);
if (rowData instanceof Date)
cell.setCellValue((Date) rowData);
else if (rowData instanceof Boolean)
cell.setCellValue((Boolean) rowData);
else if (rowData instanceof String)
cell.setCellValue((String) rowData);
else if (rowData instanceof Integer)
cell.setCellValue((Integer) rowData);
else if (rowData instanceof Long)
cell.setCellValue((Long) rowData);
else if (rowData instanceof Double)
cell.setCellValue((Double) rowData);
}
}
}
}
Related
I have created a test where I am reading from excel and iterating through a worksheet to process an application in a web portal. This is working as expected.
However I am now trying to write results from the web page into another sheet on the same excel. The test case I am running passes in Eclipse but no data is written to the specified sheet. (I'm also looking to iterate on the results sheet to capture multiple application records, haven't got to that part yet).
Please see below my test script and the methods I have created in an ExcelConfig util sheet. Hoping someone can advise where I'm going wrong, thanks in advance.
Steve
Test Case
package com.htb.puma.uatTests;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import com.htb.puma.pages.SMcaseHeader;
import com.htb.puma.pages.SMhome;
import com.htb.puma.pages.SMloanDetails;
import com.htb.puma.pages.SMlogin;
import com.htb.puma.pages.SetUpConfig;
import com.htb.puma.util.ExcelConfig;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import java.io.File;
import java.io.IOException;
public class THAM_WRITE_Test {
WebDriver driver;
#Test
public void specMortHome() throws NoAlertPresentException, InterruptedException, IOException {
// calling drivers from the SetUpConfig page
driver = SetUpConfig.getChromeDriver();
// driver = SetUpConfig.getFirefoxDriver();
// driver = SetUpConfig.getIEDriver();
String path = new File("src/test/resources/TestData.xlsx").getAbsolutePath();
ExcelConfig excel = new ExcelConfig(path);
int row = 1;
while (excel.getData("PDFRollUp", row, 0) != "") {
String loanAmReq = excel.getNumericData("PDFRollUp", row, 6);
// LOGIN
SMlogin specMortLogin = new SMlogin(driver);
specMortLogin.openSMlogin();
specMortLogin.maximiseWindow();
specMortLogin.enterUsername("OpsAdminAuto");
specMortLogin.enterPassword("AutoOps123!");
specMortLogin.clickSignInBtn();
Thread.sleep(2000);
SMhome specMortHome = new SMhome(driver);
specMortHome.clickTopMC();
Thread.sleep(2000);
SMcaseHeader specMortCaseHeader = new SMcaseHeader(driver);
specMortCaseHeader.clickLoanDetailsTab();
SMloanDetails specMortLoanDetails = new SMloanDetails(driver);
Thread.sleep(2000);
specMortLoanDetails.enterLoanAmReq(Keys.CONTROL + "a"); // PDF
specMortLoanDetails.enterLoanAmReq(loanAmReq); // PDF
String erc = specMortLoanDetails.getERC();
String ltv = specMortLoanDetails.getLTV();
excel.createFile("src/test/resources/TestData.xlsx");
excel.writeStringData("Results", 1, 1, erc);
excel.writeStringData("Results", 1, 2, ltv);
specMortHome.clickUserActionsHomeLM();
specMortHome.clickLogoutHomeLM();
row++;
}
driver.quit();
}
}
Excel Config
package com.htb.puma.util;
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;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class ExcelConfig {
public XSSFWorkbook wb;
XSSFSheet sheet1;
public ExcelConfig(String Excelpath) {
File src = new File(Excelpath);
try {
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
System.out.println("Excel file not loaded");
}
}
// reads the string in the excel file
public String getData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
data = sheet1.getRow(row).getCell(column).getStringCellValue();
} catch (NullPointerException e) {
data = "";
}
return data;
}
// reads the number in the excel file
public String getNumericData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
// data = sheet.getRow(row).getCell(column).getRawValue();
DataFormatter dataFormatter = new DataFormatter();
Cell cell = sheet1.getRow(row).getCell(column);
data = dataFormatter.formatCellValue(cell);
} catch (NullPointerException e) {
data = "";
}
return data;
}
//write string data into excel
public void writeStringData(String sheetName, int row, int column, String data) {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
}
//creates an excel file
public void createFile(String path) {
File src = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(src);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
write(java.io.OutputStream stream) is used to write data to the excel file
public void writeStringData(String sheetName, int row, int column, String data) {
try {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
FileOutputStream fout;
fout = new FileOutputStream(new File("<path>"));
//fout = new FileOutputStream("src/test/resources/TestData.xlsx" );
wb.write(fout);
// fout.flush();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Here is my excel utils class:
package utility;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell cell;
private static XSSFRow row;
//This method is to set the File path and to open the Excel
file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
String cellData = "";
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(CellType.STRING);
cellData = cell.getStringCellValue();
return cellData;
} catch (Exception e) {
return "undefined";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try {
row = ExcelWSheet.getRow(RowNum);
cell = row.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
cell = row.createCell(ColNum);
cell.setCellValue(Result);
} else {
cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData + Constants.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the script where I'm calling the getCellData to get the values from Excel:
String cellData = ExcelUtils.getCellData(1, 1);
System.out.println("CellData :" + cellData);
Here is the excel file format:
TestCaseName | Username | Password
TC_01 | TestData |
Output:
Exception in thread "main" java.lang.NullPointerException
at utility.ExcelUtils.getCellData(ExcelUtils.java:63)
at testScripts.Category_creation.main(Category_creation.java:47)
Here is the excel I'am using. Not able to fetch data from excel file. I'm using Page object framework, hence the excel utils file contains only the code and in fetching the data in testScript by passing row and column number.
POI 3.9
please add cell.setCellType(Cell.CELL_TYPE_STRING); after cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
i.e.
import org.apache.poi.ss.usermodel.Cell;
...
try{
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(Cell.CELL_TYPE_STRING);
String CellData = cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
or you can use this construct
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
source http://www.java67.com/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html
and please rename the variable private static XSSFCell Cell; to cell. (Variable naming conventions in Java?)
UPDATE 1
POI 3.17 you could also uncomment switch-case block, it works for POI 3.17
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellType;
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;
public class Excel {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell xCell;
private static XSSFRow xRow;
public static void main(String... args) {
try {
InputStream is = readInputStreamFromFile();
XSSFWorkbook myWorkBook = new XSSFWorkbook(is);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
ExcelWSheet = mySheet;
System.out.println(getCellData(1, 0));
System.out.println(getCellData(1, 1));
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception{
try {
String cellData = "";
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
xCell.setCellType(CellType.STRING);
cellData = xCell.getStringCellValue();
// switch (xCell.getCellTypeEnum()) {
// case STRING:
// //System.out.print(xCell.getStringCellValue() + "\t");
// cellData = xCell.getStringCellValue();
// break;
// case NUMERIC:
// cellData = String.valueOf(xCell.getNumericCellValue());
// //System.out.print(xCell.getNumericCellValue() + "\t");
// break;
// case BOOLEAN:
// cellData = String.valueOf(xCell.getBooleanCellValue());
// //System.out.print(xCell.getBooleanCellValue() + "\t");
// break;
//
// default:
// cellData = "undefined";
// }
return cellData;
} catch (Exception e){
return "undefined";
}
}
private static InputStream readInputStreamFromFile() throws Exception {
try {
File f = new File("C:\\path to your file\\TestData.xlsx");
InputStream is = new FileInputStream(f);
try {
return new ByteArrayInputStream(IOUtils.toByteArray(is));
} finally {
is.close();
}
} catch (IOException e) {
throw new Exception(e);
}
}
}
i want to get the (valid and invalid) data from excel .xls file and apply that in my application login page.when the error message is display.i want to write failed in excel file.from my code, i can get the value from excel and apply it in my application but cant write the output in excel.i attached my code here.anyone please help me to fix this.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
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.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class exceltowrite {
public FileInputStream fis = null;
public FileOutputStream fos = null;
public HSSFWorkbook workbook = null;
public HSSFSheet sheet = null;
public HSSFRow row = null;
public HSSFCell cell = null;
String xlFilePath;
public exceltowrite(String string, String xlFilePath) throws IOException {
this.xlFilePath = xlFilePath;
fis = new FileInputStream(xlFilePath);
workbook = new HSSFWorkbook(fis);
fis.close();
}
public static void main(String[]args) throws EncryptedDocumentException, InvalidFormatException, IOException, InterruptedException {
for(int i=1;i<=29;i++) {
String u1 =exceltowrite.getdata(i,0);
String p1=exceltowrite.getdata(i,1);
WebDriver d1=new FirefoxDriver();
d1.get("http:\\www.google.com");
d1.get("napplication site");
d1.findElement(By.name("AdminLoginForm[email]")).sendKeys(u1);
d1.findElement(By.name("AdminLoginForm[password]")).sendKeys(p1);
d1.findElement(By.name("login-button")).click();
Thread.sleep(2000);
WebElement e1= d1.findElement(By.xpath("email error message path"));
String s1=e1.getText();
WebElement e2=d1.findElement(By.xpath("password error message path"));
String s2=e2.getText();
if(s1.equals("Email cannot be blank.")) {
System.out.println("emailid failed");
d1.quit();
if(s2.equals("Password cannot be blank.")) {
System.out.println("password failed");
d1.quit();
} else {
System.out.println("password pass");
d1.quit();
}
} else {
d1.quit();
}
}
}
public static String getdata(int i, int j) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream fis=new FileInputStream("file path");
Workbook wb=WorkbookFactory.create(fis);
String s=wb.getSheet("Sheet1").getRow(i).getCell(j).getStringCellValue();
return s;
}
public boolean setCellData(String sheetName, int colNumber, int rowNum, String value)
{
try
{
sheet = workbook.getSheet(sheetName);
row = sheet.getRow(rowNum);
System.out.println(row);
cell = row.getCell(colNumber);
System.out.println(cell);
cell.setCellValue(value);
fos = new FileOutputStream(xlFilePath);
workbook.write(fos);
fos.close();
System.out.println("Finished");
}
catch (Exception ex)
{
ex.printStackTrace();
return false;
}
return true;
}}
}
my another class is this
public class Demo {
public static void main(String args[]) throws Exception
{
// exceltowrite at=new exceltowrite("file path");
for(int j=0;j<=29;j++){
at.setCellData("Sheet1",2,j,"failed");
}}}
public static void write() throws IOException {
String home = System.getProperty("user.home");
String downlpad = home + "\\Downloads";
File file = new File(downlpad + "\\" + "Suhit-File-to-Download.xlsx");
FileOutputStream outputStream = new FileOutputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Java Books");
ArrayList<Object> bookData = new ArrayList<>();
bookData.add("Name");
bookData.add("Address");
bookData.add("Number");
XSSFRow row = sheet.createRow(0);
for (int i = 0; i < bookData.size(); i++) {
XSSFCell cell3 = row.createCell(i);
cell3.setCellValue((String) bookData.get(i));
}
workbook.write(outputStream);
workbook.close();
}
I am creating an excel sheet using Apache POI and then sending the same file using Java GWT.The file created is all right.Now in the mail there are two options- Save or open.When I save the file in machine it is working fine but when I try to open ,it opens in notepad.In the suggestion too it is not showing excel. Here is my code to create the excel sheet:
package com.ericsson.egi.sxs.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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;
import com.ericsson.egi.sxs.persistence.entity.AssetOrder;
public class CreateExcelFile {
int rownum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
CreateExcelFile() {
}
public File createWeeklyReport(List<AssetOrder> tempOrderList) throws Exception {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
List<String> headerRow = new ArrayList<String>();
headerRow.add("Name of Supplier/Vendor");
headerRow.add("Description of Contract");
headerRow.add("Initiator");
headerRow.add("Type Of Contract");
headerRow.add("Template Source");
headerRow.add("Savings");
headerRow.add("Payment Term");
headerRow.add("Code of Conduct Signed by Supplier");
headerRow.add("RoHS clause Included");
headerRow.add("Agreement No");
headerRow.add("Agreement Validity From ");
headerRow.add("Agreement Validity To");
headerRow.add("Sanctioned Parties List Screening");
headerRow.add("Sanctioned Parties List Screening Reasons in case no answer NO");
headerRow.add("Registered in CLM");
headerRow.add("Registered in CLM reasons if answer NO");
headerRow.add("Current State");
headerRow.add("Next State");
headerRow.add("TAT for L1");
headerRow.add("TAT for L2");
headerRow.add("TAT for L3");
headerRow.add("TAT for L4");
headerRow.add("Current State Comments");
List<List> recordToAdd = new ArrayList<List>();
recordToAdd.add(headerRow);
for (AssetOrder order : tempOrderList ) {
List<String> row = new ArrayList<String>();
row.add(order.getSourcingDetails().getVendorName());
row.add(order.getSourcingDetails().getContractDescription());
row.add(order.getSourcingDetails().getInitiatorName());
row.add(order.getSourcingDetails().getContractType());
row.add(order.getSourcingDetails().getTemplateSource());
row.add(order.getSourcingDetails().getSavings());
row.add(order.getSourcingDetails().getPaymentTerm());
if (order.getSourcingDetails().getIsCOCSigned()) {
row.add("YES");
} else {
row.add("NO");
}
if (order.getSourcingDetails().getIsROHSIncluded()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getAgreementNo());
row.add(order.getSourcingDetails().getValidityFrom().toString());
row.add(order.getSourcingDetails().getValidityTo().toString());
if (order.getSourcingDetails().getIsSPLScreening()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForSPL());
if (order.getSourcingDetails().getIsRegisteredInCLM()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForCLM());
row.add(order.getStatusMaster().getStatusName());
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(order.getComments());
recordToAdd.add(row);
}
CreateExcelFile cls = new CreateExcelFile(recordToAdd);
File file = cls.createExcelFile(tempOrderList.get(0).getOrderRequesterSignum());
return file;
}
File createExcelFile(String requesterSignum) {
FileOutputStream fos = null;
File file = new File("/tmp/" + requesterSignum + "_StatusReport.xls");
try {
fos=new FileOutputStream(file);
HSSFCellStyle hsfstyle=workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short)245);
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
CreateExcelFile(List<List> l1) throws Exception {
try {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2= l1.get(j);
for(int k=0; k<l2.size(); k++)
{
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Try with other Excel Extension as per your Excel version installed on your machine.
--EDIT--
May be the issue is related to Content Type. Please confirm what are you using for this?
response.setContentType("APPLICATION/OCTET-STREAM");
// try this one if above doesn't work
//response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");
I wrote a code for writing data in an Excel sheet.In this i have to write the data in multiple cells.But it is showing some Errors.For one cell it is able to change the data.I kept for loop for changing the data in multiple cells.For this it is showing Error.
Can any one tell me that where i did mistake.
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;
import java.lang.String;
import javax.swing.JOptionPane;
import jxl.Cell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.ss.formula.functions.Column;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Sele1
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
String FileName = "C:\\Users\\u304081\\Desktop\\Java\\new.xlsx";
try
{
FileInputStream fileInputStream3 = new FileInputStream(FileName);
File outputsheetfile1 = new File(FileName);
if(outputsheetfile1.exists())
{
System.out.println("File existed");
try
{
XSSFWorkbook ObjWorkBook = new XSSFWorkbook(fileInputStream3);
XSSFSheet DriverTableSheet = ObjWorkBook.getSheetAt(0);
for(int i=1;i<3;i++)
{
XSSFRow row1 = DriverTableSheet.getRow(i);
XSSFCell Cell1 = row1.getCell(0);
System.out.println("Cell1"+ Cell1);
//System.out.println("Cell2"+ Cell2);
String str = "Abc";
Cell1.setCellValue(str);
FileOutputStream out1 = new FileOutputStream (FileName,false);
ObjWorkBook.write(out1);
fileInputStream3.close();
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Error I am getting is:
ObjWorkBook.write(out1);
`"poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"`
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Course Pack Resolution Details");
outputFileName = outPut.getAbsolutePath();
int rownum = 0;`enter code here`
for (int i = 0; i < dataList.size(); i++) {
Object[] objArr = dataList.get(i);
HSSFRow row = sheet.createRow(rownum++);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
sheet.autoSizeColumn((short) cellnum);
if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}
if (outPut.exists()) {
outPut.delete();
}
FileOutputStream out =
new FileOutputStream(outPut);
workbook.write(out);
DataList is ArrayList of Array Object so you can enter as much data as you want init.
Example of DataList:
dataList.add(new Object[]{"Sr No.", "Cols1", "cols2", "cols3"......."colsn"});
respective data you can insert in list. this example is for .xls format if you want .xlsx then use xssfworkbook.
May be help you.
The error you mentioned:
ObjWorkBook.write(out1); Here it is showing Error as "poi-bin-3.9-20121203\poi-3.9\poi-ooxml-3.9-20121203.jar has no source attachment"
Does not seem to be anyways related to the problem you mentioned about writing data in multiple cells to excel.
You may want to look at this:
How can I link source to a jar package in eclipse?
=======write data in excel-file in play framework===============
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
Map<String, Object[]> data = new HashMap<String, Object[]>();
data.put("1", new Object[] {"empNo.", "name", "salary"});
data.put("2", new Object[] {1, "John", 1500000d});
data.put("3", new Object[] {2, "Sam", 800000d});
data.put("4", new Object[] {3, "Dean", 700000d});
Set<String> keyset = data.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = data.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Integer)
cell.setCellValue((Integer)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
//new excel file created by fileoutput stream object
FileOutputStream out =
new FileOutputStream(new File("/home/jagasan/workspace-playexcelApp/public/ExcelFile3.xlsx"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ok("file reading is completed");
=======read data from excel and store in database in playframework=======
public class Application extends Controller {
/*
* public Result index() { return
* ok(index.render("Your new application is ready.")); }
*/
public Result readExcel() throws FileNotFoundException {
try{
InputStream ExcelFileToRead = new FileInputStream("/home/jagasan/workspace-play/excelApp/public/ExcelFile3.xlsx");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
boolean flag=false;
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
if(flag==false)
{
flag=true;
continue;
}
Iterator cells = row.cellIterator();
ExcelFile excelfile=new ExcelFile();
int i=0;
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
if(i==0)
excelfile.setEmpNo((int)cell.getNumericCellValue());
if(i==1)
excelfile.setName(cell.getStringCellValue());
if(i==2)
excelfile.setSalary(cell.getNumericCellValue());
i++;
}
excelfile.save();
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("error");
}
return ok("successful");
}
======in build.sbt=======
use the dependency jar file means apache API
libraryDependencies ++= Seq(
javaJdbc,
cache,
javaWs,
"org.apache.poi" % "poi" % "3.8", "org.apache.poi" % "poi-ooxml" % "3.9"
)