The scenario is roughly this:
I have a java program with several methods getting called randomly.
The first method will create an xls file using apache POI and will put the headers for the columns.
All the other methods has to write a record into this file.
The final method will first mail the created xls and then delete the xls.
For above scenario is the below approach correct:
1) Create the file and put the header names in the first method:
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short)0);
row.createCell(1).setCellValue(createHelper.createRichTextString("First Column"));
row.createCell(2).setCellValue(createHelper.createRichTextString("Second Column"));
row.createCell(3).setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
2) In the remaining methods put the records:
I am not sure of the code here. I know that I can reach the end of the sheet using getRowCount method and then add the new row. But I could not find any example code.
Also, how to access the existing xls file ?
3) In the last method, the file will be mailed and then deleted.
Do I need to perform any other steps before deleting the file ?
This was what I was looking for:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
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.Font;
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 PoiWriteExcelFile {
public void methodOne() {
System.out.println("Into method one!");
Workbook wb = new HSSFWorkbook();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
CellStyle cs = wb.createCellStyle();
cs.setFont(f);
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short) 0);
Cell c = null;
c = row.createCell(0);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("First Column"));
c = row.createCell(1);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Second Column"));
c = row.createCell(2);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method one!");
}
public void methodTwo() {
System.out.println("Into method two!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("First Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("First Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("First Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method two!");
}
public void methodThree() {
System.out.println("Into method three!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("Second Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("Second Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("Second Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method three!");
}
public void methodFour() {
System.out.println("Into method four!");
File file = new File("C:\\TestData\\POI\\poi-test.xls");
// file.deleteOnExit();
System.out.println("Out of method four!");
}
public static void main(final String[] args) {
PoiWriteExcelFile myObj = new PoiWriteExcelFile();
myObj.methodOne();
myObj.methodTwo();
myObj.methodThree();
myObj.methodFour();
}
}
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();
}
}
Earlier I was using SAX parser for export to excel. Now I am not able to get data using Apache POI, Any suggestion???
This String in XML contains all the data which I retrieved through farpoint grid tech and set in the form in action class.
private void parseXML(String inXML) {
/* // get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file
sp.parse(new InputSource(new StringReader(inXML)), this);
} catch (IOException ie) {
}*/
Now I am using this.
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue(inXML);
**/* Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellValue(inXML);
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}*/**
try {
FileOutputStream out = new FileOutputStream(new File("C:\\Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This program (which is what you posted with added imports, without the comment block, with a literal string instead of the variable inXML and with the path removed from the output file):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.ss.usermodel.Cell;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
HSSFRow row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue("<data>test data</data>");
try {
FileOutputStream out = new FileOutputStream(new File("Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Produced exactly what you would expect: A spreadsheet with <data>test data</data> in cell A1.
Perhaps cell A1 in your spreadsheet is blank because inXML really is blank.
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");
There is a excel file which is having lot of file names in one of its column . I need to write a java code that should read those file names and generate the same in destination.Can any one help me ?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
FileOutputStream outFile =new FileOutputStream(new File("C:\\"+cell.getStringCellValue()));
workbook.write(outFile);
}
System.out.println("");
}
file.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
There are some libraries you can use to read excel files. In my case, I chose the Apache POI which you can download for free and then add to your project. Once you added it, create your Document:
HSSFWorkbook workbook = new HSSFWorkbook( new FileInputStream("filename.xls") );
or, if it's an excel document from 2007 or later:
XSSFWorkbook workbook = new XSSFWorkbook( new FileInputStream("filename.xlsx") );
Now you can iterate through each row and read out the first column:
for( Row row : workbook.getSheetAt(0) ) // Go through each row in sheet 0
System.out.println( row.getCell(0).getStringCellValue() );
public class Test {
public static void main(String[] args) throws IOException {
try {
FileInputStream file = new FileInputStream(new File("D:\\sampleFileNames.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
FileOutputStream outFile= null;
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
Cell cell = cellIterator.next();
File file1 = new File("D:\\Ganesh\\"+cell.getStringCellValue().toString());
if(!file1.createNewFile()) {
System.out.println("File already exists");
/* Cell cell = cellIterator.next();
System.out.print(cell.getStringCellValue() + "\t\t");
outFile =new FileOutputStream(new File("D:\\Ganesh\\"+cell.getStringCellValue().toString()));
//workbook.write(outFile);
System.out.println("");
}
file.close();
outFile.close();
/* FileOutputStream outFile =new FileOutputStream(new File("C:\\update.xls"));
workbook.write(outFile);*/
//outFile.close();
}
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I'm trying to create an excel spreadsheat in my seam java application. This is my setup:
web.xml:
<servlet>
<servlet-name>Document Store Servlet</servlet-name>
<servlet-class>org.jboss.seam.document.DocumentStoreServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Document Store Servlet</servlet-name>
<url-pattern>/seam/docstore/*</url-pattern>
</servlet-mapping>
export.xhtml:
<s:resource xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.com/products/seam/taglib"
data="#{showSoldArticlesBean.excelData()}"
contentType="application/vnd.ms-excel"
fileName="#{showSoldArticlesBean.excelFileName()}"/>
someother.xhtml:
<s:download src="/export/export.xhtml">
<h:outputText value="Download excel"/>
</s:download>
ShowSoldArticlesBean
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.*;
import java.io.*;
import java.util.List;
#Name("showSoldArticlesBean")
#AutoCreate
#MeasureCalls
#Scope(ScopeType.CONVERSATION)
public class ShowSoldArticlesBean implements Serializable {
#In
private ArticleAdminBean articleAdminBean;
#In(required = false)
#Out(required = false)
private String fromDate;
#In(required = false)
#Out(required = false)
private String toDate;
#Out(required = false)
List<Article> currentArticleList;
#Begin
public void initiatePage() {
if (StringUtils.isBlank(fromDate) && StringUtils.isBlank(toDate)) {
fromDate = aWeekAgo();
toDate = dateToString(now());
this.showSoldArticles();
}
}
#End
public void showSoldArticles() {
currentArticleList = articleAdminBean.getArticles(fromDate, toDate);
}
public byte[] excelData() {
OutputStream fos = null;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
HSSFFont font = workbook.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short) 20);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.BLUE.index);
style.setFont(font);
HSSFRow row = sheet.createRow(1);
HSSFCell cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("Doing some excel crazy stuff!"));
cell.setCellStyle(style);
sheet.autoSizeColumn((short) 1);
fos = null;
try {
fos = new FileOutputStream(new File(this.excelFileName()));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return workbook.getBytes();
}
public String excelFileName() {
return "Somecrap.xls";
}
}
pom.xml:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8-beta4</version>
</dependency>
This code generates an excel file that excel complains about and states that the file is corrupt. If I choose to repair the file I get the file with the correct data.
Could you please help me and explain where I'm wrong.
I guess that sometimes drinking on the job doesn't help you perform better as a programmer =))
I have no idea what was going on in my head when I chose to return the bytes instead of the file.
Thank you Gagravarr for pointing that out.
Correct code:
public File excelData() {
File excel = new File("Somecrap.xls");
OutputStream fos = null;
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
style.setFillBackgroundColor(HSSFColor.GREY_25_PERCENT.index);
HSSFFont font = workbook.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short) 20);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
font.setColor(HSSFColor.BLUE.index);
//style.setFont(font);
HSSFRow row = sheet.createRow(1);
HSSFCell cell = row.createCell(1);
cell.setCellValue(new HSSFRichTextString("Doing some excel crazy stuff!"));
//cell.setCellStyle(style);
sheet.autoSizeColumn((short) 1);
fos = null;
try {
fos = new FileOutputStream(excel);
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return test;
}
public String excelFileName() {
return "Somecrap.xls";
}