Getting null pointer exception while reading excel file data [duplicate] - apache-poi

This question already has an answer here:
How to read multiple rows and columns in excel file with apache poi?
(1 answer)
Closed 4 years ago.
#Test
public void dataProviderMethod() throws InvocationTargetException, FileNotFoundException
{
try
{
File src=new File("D:\\TestData.xls");
FileInputStream fis=new FileInputStream(src);
HSSFWorkbook wb=new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
int rowcount=sheet.getLastRowNum()+1;
System.out.println(rowcount);
for(int i=1; i<rowcount;i++)
{
String questionType=sheet.getRow(i).getCell(0).getStringCellValue().toString();
System.out.println(questionType);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

You need to modify the code logic as below. Since, Some of the cell has blank value and hence null pointer exception is throwing. We need to handle the NULL Cell Value as below
Modified For loop Code:
//Column Index
int column=0;
for(int i=1; i<rowcount;i++){
Row r=sheet.getRow(i);
Cell c=r.getCell(column, Row.RETURN_BLANK_AS_NULL);
if(c==null){
questionType="";
}
else{
questionType=r.getCell(column).getStringCellValue();
}
System.out.println(questionType);
}

Related

Read excel content after get data from particular cell

I have existing codes that work to get a particular cell from an excel sheet.
is that possible to read particular content within the cell?
excel reader:
public String ReadCellData(int vRow, int vColumn)
{
String value=null; //variable for storing the cell value
Workbook wb=null; //initialize Workbook null
try
{
//reading data from a file in the form of bytes
FileInputStream fis=new FileInputStream(RunConfiguration.getProjectDir() + "/Data Files/testmatrix.xlsx");
//constructs an XSSFWorkbook object, by buffering the whole stream into the memory
wb=new XSSFWorkbook(fis);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e1)
{
e1.printStackTrace();
}
Sheet sheet=wb.getSheetAt(0); //getting the XSSFSheet object at given index
Row row=sheet.getRow(vRow); //returns the logical row
Cell cell=row.getCell(vColumn); //getting the cell representing the given column
//value=cell.getStringCellValue(); //getting cell value
//return value; //returns the cell value
}
}
codes to get and print data
//read excel cell C11, ignore first row column A1. (int vRow, int vColumn)
def exceldata = CustomKeywords.'test.readexcel.ReadCellData'(11, 2)
String jsondata = JsonOutput.prettyPrint(exceldata.toString())
println(jsondata)
WebUI.delay(1)
//call the object and post the above data as API HTTP request body
def post = ((findTestObject('Object Repository/Web Service Request/test-service/Post')) as RequestObject)
post.setBodyContent(new HttpTextBodyContent(jsondata))
WebUI.delay(2)
//POST and verification
def response = WS.sendRequestAndVerify(post)
println(response.statusCode)
assert response.getStatusCode() == 201
excel data at Cell C11
I want to get the value of key testId.
{
"testId": "test123",
"created": "2020-02-06T17:02:39.257Z",
}
You will need to parse the response:
def parsedResponse = new JsonSlurper().parseText(response.getResponseText())
println parsedResponse.get("testId")
(don't forget to import groovy.json.JsonSlurper)

PX.Data.XLSXReader not reading first row

I'm using the XLSXReader to read an Excel file, but it is failing to read the first row. I need to read the first row since it contains data and not headers.
Using test data, I put in a blank first row, but it still skipped the first row with data:
I copied the first row and duplicated it and it read the row:
I don't know why it is automatically skipping the first row.
Here is the action button code that imports the file, saves it, and reads it:
public PXAction<PMProject> importCostBudget;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Import Cost Budget")]
protected void ImportCostBudget()
{
if (ImportCostBudgetView.AskExt() == WebDialogResult.OK)
{
const string PanelSessionKey = "ImportCostBudget";
PX.SM.FileInfo info = (PX.SM.FileInfo)PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[PanelSessionKey];
Byte[] bytes = info.BinData;
System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
if (info != null)
{
PXNoteAttribute.AttachFile(Base.Project.Cache, Base.Project.Current, info);
using (PX.Data.XLSXReader reader = new XLSXReader(bytes))
{
//List<PMCostBudget> costBudgets = new List<PMCostBudget>();
reader.Reset();
//This is to read the first row
RowRead(reader);
while (reader.MoveNext())
{
RowRead(reader);
}
}
}
}
}
Is there a way I can force read the very first row using the reader?
Header row is likely treated as a special case intended for reading column names.
You should be able to access it from the XLSXReader IndexKeyPairs collection:
public IDictionary<int, string> IndexKeyPairs
{
get { return _header; }
}

Need help understand how Strings work in my method

I am trying to understand how this convertingStringToInt method works. I am reading a file, storing the values in an array and am to pass those values to the method to be converted. In the parameters of convertingStringToInt, I have (String number) I don't get where the String "number" is getting its values. So I am passing in a string called numbers, but how is that newly created String associated with any of the values in my file...?!?
I am trying to understand the cause all the return numbers are the error code -460 except the last digit in the file. So the String numbers is associated with the file somehow I just don't get how...
public static void read_file()
{
try {
File file = new File("randomNumbers.txt");
Scanner scan = new Scanner(file);
int amountOfNumbersInFile = convertingStringToInt(scan.nextLine()); // read the first line which is 100 to set array size
global_numbers = new int[amountOfNumbersInFile]; // set the array size equal to the first line read which is 100
for (int index = 0; index < amountOfNumbersInFile; index++)
{
String line = scan.nextLine();
global_numbers [index] = convertingStringToInt(line);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
public static int convertingStringToInt(String numbers) //what does string "number" equal? why/where is it declared?
{
String numbers = scan.nextInt();
try {
return Integer.parseInt(numbers);
} catch (NumberFormatException n) {
return -460;
}
}
I have global_numbers declared as a global variable.
so the first thing u need understand is what u have in your txt file
if in this file you have only number is ok use stringToInt
but if you have words this never work properly

How to lock a specified row using Apache POI?

I am using Apache POI to write data to an Excel file,and I want to make the first row readonly and the the other rows can be edit at any time.But I did not find an effective way to solve it.
Below is my code:
public static void createExcel(){
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet=workbook.createSheet("Variable");
CellStyle lockStyle=workbook.createCellStyle();
lockStyle.setLocked(true);
CellStyle unlockStyle=workbook.createCellStyle();
unlockStyle.setLocked(false);
sheet.protectSheet("www.hirain.com");
for(int i=0;i<=20;i++){
Row row=sheet.createRow(i);
if(i==0){
row.setRowStyle(lockStyle);
}else{
row.setRowStyle(unlockStyle);
}
Cell c1=row.createCell(0);
Cell c2=row.createCell(1);
c1.setCellValue((char)i);
c2.setCellValue(String.valueOf((char)(65+i)));
}
try {
OutputStream out=new FileOutputStream(new File("D:\\test.xls"));
workbook.write(out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("=========export excel success=========");
}
It seems this java code block should work,but in fact it will not only lock the first row but also lock the empty cells in other row.
So I want to know is there an effective way to only lock the first row of the excel file using apachepoi?
its work for me
if(y==0) {
unlockedCellStyle.setLocked(true);
sheet.lockFormatCells(true);
sheet.enableLocking();
}else {
unlockedCellStyle.setLocked(false);
sheet.lockFormatCells(false);
sheet.enableLocking();
}
cell.setCellStyle(unlockedCellStyle);

System.AccessViolationException while initializing an array

void BinaryTree::InitializeFromFile(string Filename){
ifstream inFile;
treenode* Freq[256];
inFile.open(Filename.c_str(), fstream::binary);
if(inFile.fail()){
cout<<"Error in opening file "<<Filename;
return;
}
for(int i=0;i<=255;i++){
Freq[i]->weight=0;
Freq[i]->data = '0'+i;
Freq[i]->LChild = NULL; Freq[i]->RChild=NULL; Freq[i]->Parent=NULL;
}
char c;
inFile.get(c);
while(!inFile.eof()){
Freq[c]->weight ++;
inFile.get(c);
}
}
I'm getting the Access Violation Exception in the for loop. Even when I comment out certain lines it'll give me an error on the next line in that loop.
Edit: Also is the line Freq[c]->weight ++; valid? Can I go to a specific part of the array based on the char value?
You seem to never initialize your Freq table. It contains random pointers. Dereferncing an uninitialized pointer leads to undefined behaviour.
You ought to add Freq[i] = new treenode before Freq[i]->weight=0;.

Resources