I want to export all the data from one workbook to another using Java. I used FOR LOOP to read all the data from the input.xls file. Then I want to Export all the read data to output.xls. I don't know how to export it after reading data. I need your help guys. Thanks.
HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream("C:\\input.xls"));
FileOutputStream wbML = new FileOutputStream("C:\\output.xls");
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
String sValue = cell.getRichStringCellValue().getString();
System.out.println(sValue);
}
}
If you just want to copy the workbook, there is no need to iterate. Just write it to a new file.
Workbook wb = new HSSFWorkbook(new FileInputStream("C:\\input.xls"));
FileOutputStream fileOut = new FileOutputStream("C:\\ouput.xls");
wb.write(fileOut);
fileOut.close();
Related
When I add data to second tab in excel sheet. First tab data is not displaying.
If i remove code for second tab, first tab data is visible.
HSSFSheet sheet1 = wb.createSheet("A ");
HSSFSheet sheet2 = wb.createSheet("B");
HSSFFont headerFont = wb.createFont();
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headerStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
headerStyle.setFillBackgroundColor(HSSFColor.WHITE.index);
headerStyle.setFont(headerFont);
try
{
FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls");
HSSFRow sessionname = sheet1.createRow(0);
HSSFCell title = sessionname.createCell(0);
title.setCellStyle(headerStyle);
title.setCellValue("Supported cipher Report");
HSSFRow row = sheet1.createRow(5);
HSSFCell cell0 = row.createCell(0);
cell0.setCellStyle(headerStyle);
cell0.setCellValue("One");
HSSFCell cell1 = row.createCell(1);
cell1.setCellStyle(headerStyle);
cell1.setCellValue("two");
HSSFCell cell2 = row.createCell(2);
cell2.setCellStyle(headerStyle);
cell2.setCellValue("three");
HSSFCell cell3 = row.createCell(3);
cell3.setCellStyle(headerStyle);
cell3.setCellValue("four");
HSSFCell cell4 = row.createCell(4);
cell4.setCellStyle(headerStyle);
cell4.setCellValue("five");
if (!list.isEmpty())
{
int rowNumber = 6;
for (Result s : supportedlist)
{
HSSFRow nextrow = sheet1.createRow(rowNumber);
nextrow.createCell(0).setCellValue(s.One());
nextrow.createCell(1).setCellValue(s.Two());
nextrow.createCell(2).setCellValue(s.Three());
nextrow.createCell(3).setCellValue(s.four());
nextrow.createCell(4).setCellValue(s.five());
rowNumber++;
}
}
sheet1.autoSizeColumn(0);
sheet1.autoSizeColumn(1);
sheet1.autoSizeColumn(2);
sheet1.autoSizeColumn(3);
sheet1.autoSizeColumn(4);
System.out.println("sheet1 writting");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
when i pass sheet2 and remaining code is same as above.
sheet1 tab data is not displayed while sheet2 data is desplayed.
I think what you are doing is you are changing the values of sheet1 to sheet2 after writing to sheet1. Now, what happens according to your code is you are again creating/writing to a file. So, it replaces the old file and data and writes to a new file in second sheet.
Below line overwrites the data when you run the program second time
FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls");
What you should do is when writing to sheet2 you should check if file exists or not. If exists then it adds new sheet to existing excel file. If not exists create a new file and then create a sheet.
Do something like this
FileOutputStream fileOut = new FileOutputStream(file);
if (file.exists()) {
try {
workbook = (HSSFWorkbook)WorkbookFactory.create(file);
} catch (InvalidFormatException e) {
e.printStackTrace();
}
HSSFSheet sheet = workbook.createSheet("Sample sheet2");
}
else{
workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet1");
}
workbook.write(fileOut);
fileOut.close();
To avoid overwriting to a existing file use below. This will append the data to the existing file.
FileOutputStream fileOut = new FileOutputStream("C:\\Report.xls", true);
problem was I created two instances[new createExcel(one); and new createExcel(two); while invoking the function. since wb is part of instance. so it created new excel with sheet1 and sheet2 inside. and since this time I write sheet2 data only. so sheet2 data was only displaying. Thanks for the support.
i am trying to edit an excel sheet using apache poi,
I have a worksheet having 2 rows and 5 columns
if second cell of row 2 is null then it should add a 3rd row ,
but i am getting a class not found exception, although the UpdateXLS is present in my D drive.
Here is the code:
public class New {
public static void main(String[] args){
try{
InputStream inp = new FileInputStream("D:\\UpdateXLS.xls");
//InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
Cell cell = row.getCell(2);
if (cell == null)
cell = row.createCell(3);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("a test");
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
wb.write(fileOut);
fileOut.close();
}
catch(Exception e){
e.printStackTrace();
}
}
What should i do ?
From the comment , I can suggest you that check file exits on the path specified.
Use File
File f = new File("D:\\UpdateXLS.xls");
//check whether file exists or not to avoid any further exceptions
if(f.exists()){
Workbook wb = WorkbookFactory.create(f);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(2);
......
.......
........
}
FileNotFoundException
Signals that an attempt to open the file denoted by a specified pathname has failed.
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist.
It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
When you are writing a file check your path
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
Change to
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
The problem seems to be at
FileOutputStream fileOut = new FileOutputStream("UpdateXLS.xls");
try to replace the line with:
FileOutputStream fileOut = new FileOutputStream("D:\\UpdateXLS.xls");
I am trying to write a excel file using Apache POI package. Here is the code snippet:
String basePath = "/home/aman/Desktop";
String fileName = "result.xls";
File file = new File(basePath, fileName); //File not null. checked.
OPCPackage pkg = OPCPackage.openOrCreate(file); //pkg not null. checked.
Workbook wb = new XSSFWorkbook(pkg); //GenerateReport.java:63
I get the following error:
Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:382)
at org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:186)
at amazon.category.database.GenerateReport.generateExcel(GenerateReport.java:63)
at amazon.category.database.MerchantAdoptionStats.processAdoptionStats(MerchantAdoptionStats.java:197)
at amazon.category.database.MerchantAdoptionStats.main(MerchantAdoptionStats.java:386)
Any help appreciated.
I found this example at the tutorial site:
here
You could try this approach.
Workbook wb = new HSSFWorkbook();
//Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("new sheet");
// Create a row and put some cells in it. Rows are 0 based.
Row row = sheet.createRow((short)0);
// Create a cell and put a value in it.
Cell cell = row.createCell(0);
cell.setCellValue(1);
// Or do it on one line.
row.createCell(1).setCellValue(1.2);
row.createCell(2).setCellValue(createHelper.createRichTextString("This is a string"));
row.createCell(3).setCellValue(true);
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
I hit my head against this one for a while myself. The trick is whether or not the file exists prior.
//if file is .xls
Workbook workbook;
if(file.exists) {
NPOIFSFileSystem fs = new NPOIFSFileSystem(file);
workbook = new HSSFWorkbook(fs.getRoot(), false);
}
else {
workbook = new HSSFWorkbook();
}
//if file is .xlsx
Workbook workbook;
if(file.exists) {
OPCPackage pkg = OPCPackage.open(file);
workbook = new XSSFWorkbook(pkg);
}
else {
workbook = new XSSFWorkbook();
}
The trick appears to be (and this doesn't look like it is documented well), that you create the workbooks off of the file system or package objects only if the file exists prior. If you want a new file, then don't use the file system or package objects to create your workbooks.
If everything is what it looks like, you should not be able to build an XSSFWorkbook on an .xls file, since it is a class to model .xlsx files. You should use WorkbookFactory.create() instead of that, which is a factory method that will return the appropiate Workbook implementation for each case
I have used POI to read from / write to excel sheets.When writing to a new sheet using POI,it worked.But, when i am trying to write in a existing excel workbook using POI, it doesnt worked.how can i correct this issue?
workBook = getWorkbookSheet(workBookName);
sheet1 = workBook.getSheetAt(1);
sheet2 = workBook.getSheetAt(2);
while(sheetStart<sheet1.getLastRowNum() + 1)
{
HSSFRow rowSheet1 = sheet1.getRow(sheetStart);
HSSFCell cellSheet1 = rowSheet1.getCell(4);
if(cellSheet1.getStringCellValue().trim().equals(valY))
{ cellSheet1.setCellValue("N");
}
else
//do nothing
sheetStart++;
}
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName());
workBook.write(fileOutSheet1);
fileOutSheet1.flush();
fileOutSheet1.close();
fileOutSheet1 = new FileOutputStream(sheet1.getSheetName()); seems not correct. you should give the path of workbook instead of sheet1.getSheetName. because you are writing the whole workbook even after a single cell content change.
for example it should be like
FileOutputStream fileOut = new FileOutputStream("C:\\MyWorkbook.xlsx");
wb.write(fileOut);
fileOut.close();
for detail visit here
InputStream inp = new FileInputStream("workbook.xls");
HSSFWorkbook wb = new HSSFWorkbook(inp);
String text="";
Sheet sheet1 = wb.getSheetAt(0);
for (Row row : sheet1) {
for (Cell cell : row) {
// Do something here
ExcelExtractor extractor = new ExcelExtractor(wb);
text=extractor.getText();
System.out.print("text="+text);
}
}
sheet1.shiftRows(0,sheet1.getLastRowNum(),1);
I am not getting the result in my excel sheet after the shiftrows is called. the data stays the same. Where am I doing it wrong?
This is because you're workbook is only open for reading since it came from an inputstream
InputStream inp = new FileInputStream("workbook.xls");
To get the result you would have to write the new workbook object out to a new xsl spreadsheet. Something like...
File outWB = new File("workbook2.xls");
OutputStream out = new FileOutputStream(outWB);
wb.write(out);
out.flush();
out.close();
You could do this to the same file but you would need to inp.close() first.