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;
}
}
Related
I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file
using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}
Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}
I want to get cell value according to the particular column name and row name.
This is the code that I have written to achieve it. It's working fine for the first sheet in the workbook but giving me Null pointer exception for the other sheet in the same workbook.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.DataFormatter;
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 ExcelReader {
public FileInputStream fis;
String path = null;
private XSSFWorkbook workbook=null;
private XSSFSheet sheet;
private XSSFRow row=null;
private XSSFCell cell=null;
public ExcelReader() throws IOException {
path = System.getProperty("user.dir") + "\\Testdata.xlsx";
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
}
public String getCellData(String sheetName, String testDataType, String testDataID) throws IOException {
sheet = workbook.getSheet(sheetName);
int i;
for(i=0;i<=sheet.getRow(0).getLastCellNum(); i++) {
row = sheet.getRow(0);
cell = row.getCell(i);
if(cell.getStringCellValue().equalsIgnoreCase(testDataType)) {
break;
}
}
for(int j=0; j<=sheet.getLastRowNum();j++) {
row = sheet.getRow(j);
cell= row.getCell(0);
DataFormatter df2 = new DataFormatter();
String valueAsString = df2.formatCellValue(cell);
if(testDataID.equals(valueAsString)) {
break;
}
}
cell=row.getCell(i);
String S= cell.getStringCellValue();
fis.close();
return S;
}
}
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);
First of all, Please Pardon me for Poor Coding!
Requirement:
1. Create xls/xlsx Report in Memory from Database ResultSet (ie. Plain Text File should not be written to Disk).
2.Create ZIP on Disk From the xlsx file in Memory.
Environment:
WinXP SP2, JDK1.6_06, Zip4j1.3.1, poi3.8
I am using Apache's POI and Zip4j and am following Mr.Shrikant's Example published at "http://www.lingala.net/zip4j/forum/index.php?topic=257.0"
Observations:
1. This program Writes 27,842 bytes xlsx file to disk for sample data.
2. The same Workbook Creates ByteArrayOutputStream,baoStream of size is 49022bytes
3. After Encryption and Zipping It Creates File of Size 43,084 bytes.
4. While Extracting Zip file,
a) WinZip, throws Error "UnExpected End of File"
b) Winrar, throws "CRC Error"
Please correct me, wherever I am wrong and improve, wherever I am poor!
Thanks in Advance!
package zipconversion;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.Types;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import net.lingala.zip4j.io.ZipOutputStream;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ZipCreationInMemory {
ZipOutputStream zos = null;
XSSFWorkbook workbook = null;
ByteArrayOutputStream baoStream = null;
String path = null;
String xlsxfileExtn = null;
String zipfileExtn = null;
String onlyFileName = null;
String xlsxFileName = null;
String zipFileName = null;
String xlsxFilePath = null;
String zipFilePath = null;
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public void createXlsxFile() {
try {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh_mm_ss");
path = "D:\\abcd\\";
xlsxfileExtn = ".xlsx";
zipfileExtn = ".zip";
onlyFileName = "ReportData_".concat(timeFormat.format(new Date()));
xlsxFileName = onlyFileName + xlsxfileExtn;
zipFileName = onlyFileName + zipfileExtn;
xlsxFilePath = path + xlsxFileName;
zipFilePath = path + zipFileName;
FileOutputStream out = new FileOutputStream(new File(xlsxFilePath));
workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Report");
XSSFRow rowHead = sheet.createRow((short) 0);
XSSFCellStyle headStyle = workbook.createCellStyle();
XSSFFont headerFont = workbook.createFont();
headerFont.setBold(true);
headerFont.setColor(new XSSFColor(new java.awt.Color(255, 0, 0)));
headStyle.setFont(headerFont);
headStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(255, 255, 255)));
headStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
XSSFCellStyle oddStyle = workbook.createCellStyle();
oddStyle.setFillForegroundColor(new XSSFColor(new java.awt.Color(randInt(125, 255), randInt(125, 255), randInt(125, 255))));
oddStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
//JDBC CONFIGURATIONS
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
String dbURL = "jdbc:derby://localhost:1527/DATABASE_NAME;create=true;user=USER_ID;password=PASSWORD";
Connection connection = DriverManager.getConnection(dbURL);
Statement st = connection.createStatement();
ResultSet resultSet = st.executeQuery("Select * from TABLE_NAME");
ResultSetMetaData metaData = resultSet.getMetaData();
int colCount = metaData.getColumnCount();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = rowHead.createCell((short) curColIndx);
cell.setCellStyle(headStyle);
cell.setCellValue(metaData.getColumnName(curColIndx + 1));
}
int index = 1;
while (resultSet.next()) {
XSSFRow row = sheet.createRow((short) index);
for (int curColIndx = 0; curColIndx < colCount; curColIndx++) {
XSSFCell cell = row.createCell((short) curColIndx);
if (index % 2 == 1) {
cell.setCellStyle(oddStyle);
}
else {
cell.setCellStyle(evenStyle);
}
int type = metaData.getColumnType(curColIndx + 1);
if (type == Types.TIMESTAMP) {
cell.setCellValue(sdf.format(resultSet.getDate(curColIndx + 1)));
} else if (type == Types.VARCHAR || type == Types.CHAR) {
cell.setCellValue(resultSet.getString(curColIndx + 1));
} else {
cell.setCellValue(resultSet.getLong(curColIndx + 1));
}
}
index++;
}
baoStream = new ByteArrayOutputStream();
try {
//This Writes 27,842 bytes xlsx file to disk for sample data.
workbook.write(out);
//same workbook is written to ByteArrayOutputStream()
workbook.write(baoStream);
//But, baoStream size is 49022bytes and After Encryption and Zipping It Creates File of Size 43,084 bytes.
System.out.println("baoStream.size() :" + baoStream.size());
try {
//byte[] bytesToWrite = getBytesFromFile();
byte[] bytesToWrite = baoStream.toByteArray();
InMemoryOutputStream inMemoryOutputStream = new InMemoryOutputStream();
zos = new ZipOutputStream(inMemoryOutputStream);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setFileNameInZip(xlsxFileName);
parameters.setSourceExternalStream(true);
zos.putNextEntry(null, parameters);
zos.write(bytesToWrite);
zos.closeEntry();
zos.finish();
zos.close();
// Write contents in our InMemoryOutputStream to a zip file to test if this worked
writeContentsToZipFile(inMemoryOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
out.close();
resultSet.close();
connection.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
System.out.println("Exception is :" + e.toString());
}
}
public ZipCreationInMemory() {
//testZipCreationInMemory();
createXlsxFile();
}
package zipconversion;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Writes the content to memory.
*
*/
public class InMemoryOutputStream extends OutputStream {
// As we cannot know the size of the zip file that is being created,
// we cannot maintain a byte array. We will copy all the bytes that
// gets passed in the write() method to a List. Once all writing is done,
// we can create a byte array from this List and this will be the content
// of the zip file
private List byteList;
// flag to keep track if the outputstream is closed
// no further write operations should be performed once this stream is closed
private boolean closed;
public InMemoryOutputStream() {
byteList = new ArrayList();
closed = false;
}
public void write(int b) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
byteList.add(Integer.toString(b));
}
public void write(byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IOException("trying to write on a closed output stream");
}
if (b != null && len > 0) {
for (int i = 0; i < len; i++) {
byteList.add(Byte.toString(b[i]));
}
}
}
public byte[] getZipContent() {
if (byteList.size() <= 0) {
return null;
}
byte[] zipContent = new byte[byteList.size()+1];
for (int i = 0; i < byteList.size(); i++) {
zipContent[i] = Byte.parseByte((String) byteList.get(i));
}
return zipContent;
}
public void close() throws IOException {
closed = true;
}
}
The bug is possible in method writeContentsToZipFile(inMemoryOutputStream), but you didn't post it's source code...
I think the implement of class InMemoryOutputStream is not required, it's not effective and cause more problem.
If you want to save the zip content to File, replace it with FileOutputStream
If you want to save the zip content in memory, replace it with ByteArrayInputStream inMemoryOutputStream = new ByteArrayInputStream(bytesToWrite.length);
Note: The first parameter of zos.putNextEntry(null, parameters) is null.
It works when parameters.setSourceExternalStream(true). Under this mode, file name and other parameters are supplied via ZipParameters.
Can someone point me in the right direction for writing to an excel file in java??
I am not understanding the links I found online.
Could you just send me a link or anything which I could follow through??
Thank you,
J
Another alternative to Apache POI is the JExcelAPI, which (IMO) has an easier to use API. Some examples:
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
Label label = new Label(0, 2, "A label record");
sheet.addCell(label);
Number number = new Number(3, 4, 3.1459);
sheet.addCell(number);
Not to be banal, but Apache POI can do it. You can find some code examples here:
http://poi.apache.org/spreadsheet/examples.html
Posting useful examples for API's.
Step by step example for using JExcelAPI:
http://www.vogella.de/articles/JavaExcel/article.html
http://www.java-tips.org/other-api-tips/jexcel/how-to-create-an-excel-file.html
Step by step example for using POI (little old one but useful):
http://www.javaworld.com/javaworld/jw-03-2004/jw-0322-poi.html
Here i'm going to give sample example,how to write excel;use this in pom.xml
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>0.9</version>
</dependency>
Model class:
public class Products {
private String productCode1;
private String productCode2;
private String productCode3;
constructors,setters and getters
}
main class:
public class WriteExcel {
public void writeExcel() {
Collection staff = new HashSet();
staff.add(new Products("101R15ss0100", "PALss Kids 1.5 A360 ", "321"));
staff.add(new Products("101R1ss50100", "PAL sKids 1.5 A360 ", "236"));
Map beans = new HashMap();
beans.put("products", staff);
XLSTransformer transformer = new XLSTransformer();
try {
transformer.transformXLS(templateFileName, beans, destFileName);
System.out.println("Completed!!");
} catch (ParsePropertyException e) {
System.out.println("In ParsePropertyException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("In IOException");
e.printStackTrace();
}
}
public static void main(String[] args) {
WriteExcel writeexcel = new WriteExcel();
writeexcel.writeExcel();
}
}
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception {
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the basic code to write data in excel file (.xls).
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.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
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.hssf.util.HSSFColor;
public class Export2Excel {
public static void main(String[] args) {
try {
//create .xls and create a worksheet.
FileOutputStream fos = new FileOutputStream("D:\\data2excel.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("My Worksheet");
//Create ROW-1
HSSFRow row1 = worksheet.createRow((short) 0);
//Create COL-A from ROW-1 and set data
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("Sno");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
//Create COL-B from row-1 and set data
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Name");
cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);
//Create COL-C from row-1 and set data
HSSFCell cellC1 = row1.createCell((short) 2);
cellC1.setCellValue(true);
//Create COL-D from row-1 and set data
HSSFCell cellD1 = row1.createCell((short) 3);
cellD1.setCellValue(new Date());
cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
cellD1.setCellStyle(cellStyle);
//Save the workbook in .xls file
workbook.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE: You need to download jar library from the link: http://www.java2s.com/Code/JarDownload/poi/poi-3.9.jar.zip
I've used Apache's POI Library when I've had to write to excel files from Java. I found it rather straight forward once you get the hang of it. Java World has a good tutorial about starting out using POI that I found very helpful.