Summary of Problem
I have created a simple program to read from and write to a spreadsheet. But it does not work. Does anyone know what I am doing wrong?
What I Have Tried
I have successfully been able to read from a spreadsheet. I have successfully been able to write to a spreadsheet. However, I cannot do both at the same time.
It seems that the createRow function overwrites the entire row. Thus, erasing previous data. This is a pretty severe constraint. It might be what is preventing me from reading and writing at the same time.
I noticed that the output says "The supplied file was empty (zero bytes long)". But I made sure that the path is correct and that there is indeed data in the spreadsheet. Not sure where that error is coming from.
I've tried following suggestions from other posts on Stack Overflow, but none of their suggestions including closing both the fileInputStream and fileOutputStream seems to affect my program at all.
My Code
package certExamPractice;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class SpreadsheetPractice {
public static void main(String[] args) throws IOException {
String path = "C:/Users/james/Desktop/Spreadsheets/Spreadsheet4.xlsx";
FileInputStream fileInputStream = new FileInputStream(path);
FileOutputStream fileOutputStream = new FileOutputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workbook.createSheet("Sheet1");
Set<String> vir = new HashSet<String>();
vir.add(sheet.getRow(0).getCell(0).getStringCellValue());
vir.add(sheet.getRow(1).getCell(0).getStringCellValue());
vir.add(sheet.getRow(2).getCell(0).getStringCellValue());
vir.add(sheet.getRow(3).getCell(0).getStringCellValue());
sheet.getRow(0).createCell(1).setCellValue("zeta");
sheet.getRow(1).createCell(1).setCellValue("eta");
sheet.getRow(2).createCell(1).setCellValue("theta");
sheet.getRow(3).createCell(1).setCellValue("iota");
System.out.println("Vir = " + vir);
workbook.write(fileOutputStream);
workbook.close();
fileOutputStream.close();
}
}
My Spreadsheet
My spreadsheet.
The Output
Exception in thread "main" org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long)
at org.apache.poi.util.IOUtils.peekFirstNBytes(IOUtils.java:112)
at org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:209)
at org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:143)
at org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:175)
at org.apache.poi.openxml4j.opc.ZipPackage.<init>(ZipPackage.java:104)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:312)
at org.apache.poi.ooxml.util.PackageHelper.open(PackageHelper.java:47)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:299)
at certExamPractice.SpreadsheetPractice.main(SpreadsheetPractice.java:18)
The following code allows you to read from and write to a spreadsheet. You need to write the beginning code and the end code. Then you can read and write as you wish in the middle.
package certExamPractice;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;
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 SpreadsheetPractice {
public static void main(String[] args) throws IOException{
//BEGINNING
String path = "C:/Users/james/Desktop/Spreadsheets/Spreadsheet4.xlsx";
FileInputStream fileInputStream = new FileInputStream(path);
Workbook workbook = WorkbookFactory.create(fileInputStream);
Sheet sheet = workbook.getSheet("Sheet1");
Row row = sheet.getRow(0);
Cell cell = row.getCell(0);
if (cell == null) { cell = row.createCell(0); }
//READ
Set<String> vir = new HashSet<String>();
vir.add(sheet.getRow(0).getCell(0).getStringCellValue());
vir.add(sheet.getRow(1).getCell(0).getStringCellValue());
vir.add(sheet.getRow(2).getCell(0).getStringCellValue());
vir.add(sheet.getRow(3).getCell(0).getStringCellValue());
System.out.println("Vir = " + vir);
//WRITE
sheet.getRow(0).createCell(1).setCellValue("zeta");
sheet.getRow(1).createCell(1).setCellValue("theta");
sheet.getRow(2).createCell(1).setCellValue("eta");
sheet.getRow(3).createCell(1).setCellValue("iota");
//END
try (OutputStream fileOutputStream = new FileOutputStream(path)) {
workbook.write(fileOutputStream);
}
workbook.close();
}
}
Related
im trying to create xlsx file with groovy.
i have Soapui open source 5.6.0
i have microsoft office 365
Running with windows 10
i added these jars is lib/ext:
commons-compress-1.20.jar
dom4j-1.6.1.jar
xmlbeans-2.6.0.jar
poi-5.0.0.jar
poi-ooxml-5.0.0.jar
poi-ooxml-schemas-3.9.jar
xmlbeans-4.0.0.jar
With this line: Workbook wb = new HSSFWorkbook();
i can create xls file for excel version 97-2003
With this line: Workbook wb = new XSSFWorkbook();
i can create xlsx file but cannot open.
What is the probleme here, i downloaded the latest jars for POI.
Do i missing something here?
Thank you for your help.
My code is:
import org.apache.poi.ss.usermodel.*
import org.apache.poi.hssf.usermodel.*
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.util.*
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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;
import org.apache.poi.ss.usermodel.CellStyle;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.*
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class CreateSheet {
public static void main(String[] args)
throws FileNotFoundException, IOException
{
// Creating xls file
//Workbook wb = new HSSFWorkbook();
// Creating xlsx file
Workbook wb = new XSSFWorkbook();
// An output stream accepts output bytes and sends them to sink.
OutputStream fileOut = new FileOutputStream("C:\\temp\\test.xlsx");
// Creating Sheets using sheet object
Sheet sheet1 = wb.createSheet("Test");
wb.write(fileOut);
}
}
It could be you're not closing the stream
try:
class CreateSheet {
static main(args) throws FileNotFoundException, IOException {
// Creating xlsx file
Workbook wb = new XSSFWorkbook()
// Creating Sheets using sheet object
Sheet sheet1 = wb.createSheet("Test")
new File("C:\\temp\\test.xlsx").withOutputStream { fileOut ->
wb.write(fileOut)
}
}
}
I have created a groovy keyword script (in Katalon) to make use of the POI XSSF to read the excel file.
but hitting an error "No such property: CellType for class: excel.readexcel" when running the test case.
I'm not sure if that is the POI library issue or I'm using the wrong syntax?
this is groovy
package excel
import java.io.IOException
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.kms.katalon.core.annotation.Keyword
public class readexcel {
#Keyword
def post(String name) throws IOException{
try {
//FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
FileInputStream fis = new FileInputStream("C:\\JY\\testmatrix.xlsx");
Workbook workbook = new XSSFWorkbook(fis);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
//getCellTypeEnum shown as deprecated for version 3.15
//getCellTypeEnum ill be renamed to getCellType starting from version 4.0
if (currentCell.getCellType() == Cell.CELL_TYPE_STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
} else if (currentCell.getCellType() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is test case to call the keyword and print the result to check if the reading successful or not.
import static com.kms.katalon.core.checkpoint.CheckpointFactory.findCheckpoint
import static com.kms.katalon.core.testcase.TestCaseFactory.findTestCase
import static com.kms.katalon.core.testdata.TestDataFactory.findTestData
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.checkpoint.Checkpoint as Checkpoint
import com.kms.katalon.core.cucumber.keyword.CucumberBuiltinKeywords as CucumberKW
import com.kms.katalon.core.mobile.keyword.MobileBuiltInKeywords as Mobile
import com.kms.katalon.core.model.FailureHandling as FailureHandling
import com.kms.katalon.core.testcase.TestCase as TestCase
import com.kms.katalon.core.testdata.TestData as TestData
import com.kms.katalon.core.testobject.TestObject as TestObject
import com.kms.katalon.core.webservice.keyword.WSBuiltInKeywords as WS
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import internal.GlobalVariable as GlobalVariable
def result = CustomKeywords.'excel.readexcel.post'('')
println(result)
error
2020-02-04 15:15:14.758 DEBUG testcase.try - 1: result = excel.readexcel.post("")
Version--Description--Date--
1.0--Test matrix for collection of test data and summary of test cases for Drug Service.--2020-02-04 15:15:16.044 ERROR k.k.c.m.CustomKeywordDelegatingMetaClass - ❌ No such property: CellType for class: excel.readexcel
2020-02-04 15:15:16.046 ERROR c.k.katalon.core.main.TestCaseExecutor - ❌ Test Cases/try FAILED.
Reason:
groovy.lang.MissingPropertyException: No such property: CellType for class: excel.readexcel
at excel.readexcel.post(readexcel.groovy:42)
at excel.readexcel.invokeMethod(readexcel.groovy)
at com.kms.katalon.core.main.CustomKeywordDelegatingMetaClass.invokeStaticMethod(CustomKeywordDelegatingMetaClass.java:50)
at try.run(try:16)
at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:337)
at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:328)
at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:307)
at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:299)
at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:233)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:114)
at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:105)
at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
at TempTestCase1580800511604.run(TempTestCase1580800511604.groovy:21)
In apache poi we are able setting zoom value using sheet.setZoom(120). But How we will get zoom values when we copy/clone same sheet. I can not able to find a method srcSheet.getZoom();. what is alternative for this method?.
What can we do if apache poi lacks a method? We could take a look how it does coding similar methods. For example XSSFSheet..setZoom does nothing else than setting the zoomScale of the default CTSheetView. So if we would get the default sheet view, we could do the opposite and get the zoomScale.
Example:
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheetView;
import java.lang.reflect.Method;
public class ExcelXSSFSheetZoom {
static long getZoom(XSSFSheet sheet) throws Exception {
Method getDefaultSheetView = XSSFSheet.class.getDeclaredMethod("getDefaultSheetView");
getDefaultSheetView.setAccessible(true);
CTSheetView sheetview = (CTSheetView)getDefaultSheetView.invoke(sheet);
return sheetview.getZoomScale();
}
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
sheet.setZoom(120);
System.out.println(getZoom((XSSFSheet)sheet));
wb.write(new FileOutputStream("ExcelXSSFSheetZoom.xlsx"));
wb.close();
}
}
I'm using this program in Keyword driven framework for selenium web driver tool. But due to this program i'm getting null pointer exception every time i tried to debug the code but cant find any solution. please suggest me the solution for that error.
package utility;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
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.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
public class ExcelUtils {
private static HSSFSheet ExcelWSheet;
private static HSSFWorkbook ExcelWBook;
private static HSSFCell Cell;
//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
{
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new HSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
}
//This method is to read the test data from the Excel cell
//In this we are passing parameters/arguments as Row Num and Col Num
public static String getCellData(int RowNum, int ColNum) throws Exception{
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
System.out.println(Cell);
String CellData = Cell.getStringCellValue();
System.out.println("."+CellData);
return CellData;
}
}
I am new to ASM. I have a class file in which I have runtime visible annotations for methods. I want to parse this class file and select the annotation according to specific criteria. I looked into the documentation of ASM and tried with the visibleAnnotation. I can't seem to print the list of annotations of method which I can see in my class files.
My code is as
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Iterator;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.ClassReader;
public class ByteCodeParser {
public static void main(String[] args) throws Exception{
InputStream in=new FileInputStream("sample.class");
ClassReader cr=new ClassReader(in);
ClassNode classNode=new ClassNode();
//ClassNode is a ClassVisitor
cr.accept(classNode, 0);
//
Iterator<MethodNode> i = classNode.methods.iterator();
while(i.hasNext()){
MethodNode mn = i.next();
System.out.println(mn.name+ "" + mn.desc);
System.out.println(mn.visibleAnnotations);
}
}
}
The output is:
<clinit>()V
null
<init>()V
null
MyRandomFunction1()V
[org.objectweb.asm.tree.AnnotationNode#5674cd4d]
MyRandomFunction2()V
[org.objectweb.asm.tree.AnnotationNode#63961c42]
My RandomFunction 1 & 2 has annotations but I can't seem to understand [org.objectweb.asm.tree.AnnotationNode#5674cd4d].
I solved this issue myself, I had to iterate over the annotations which I didn't realize initally.
if (mn.visibleAnnotations != null) {
Iterator<AnnotationNode>j=mn.visibleAnnotations.iterator();
while (j.hasNext()) {
AnnotationNode an=j.next();
System.out.println(an.values);
}
}